Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
346 views
in Technique[技术] by (71.8m points)

regex - 如何针对以下情况编写正则表达式(How do I write a regex for the following condition)

  • Should be at least 4 characters

    (至少应包含4个字符)

  • Should start with a character [a-zA-Z]

    (应以字符[a-zA-Z]开头)

  • Should not end with _

    (不应以_结尾)

  • Should only contain at most 1 _ in the entire word

    (整个单词中最多只能包含1个_)

  • The word can contain [a-zA-Z0-9]

    (该词可以包含[a-zA-Z0-9])

I tried the following regex:

(我尝试了以下正则表达式:)

^[a-zA-Z][a-zA-Z0-9]*_?[a-zA-Z0-9]*[^_]$

But then I am wondering wether this could be made even smaller, and also I am not sure how do I set 'atleast 4 characters' constraint.

(但是然后我想知道是否可以使它更小,而且我不确定如何设置“至少4个字符”约束。)

  ask by Ranjandas translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can shorten your pattern by omitting the last negated character class [^_] as that will match any char other than _ and add a positive lookahead (?=.{4}) to assert 4 character from the start of the string:

(您可以通过省略最后一个否定的字符类[^_]来缩短您的模式,因为它将匹配_以外的其他任何字符,并添加正向超前(?=.{4})以从字符串开头声明4个字符:)

^(?=.{4})[a-zA-Z][a-zA-Z0-9]*_?[a-zA-Z0-9]+$
  • ^ Start of string

    (^字符串开头)

  • (?=.{4}) Assert 4 chars

    ((?=.{4}) 4个字符)

  • [a-zA-Z] Match a single char a-zA-Z

    ([a-zA-Z]匹配一个字符a-zA-Z)

  • [a-zA-Z0-9]*_?[a-zA-Z0-9]+ Match an optional _ and any of the listed on the left and/or right

    ([a-zA-Z0-9]*_?[a-zA-Z0-9]+匹配可选的_和左侧和/或右侧列出的任何一个)

  • $ End of string

    ($字符串结尾)

Regex demo

(正则表达式演示)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...