开发者

Regular expression. Begins with and not equal to

I have a string that needs to be validated.

The first two characters must be made up A-G, or Z, but cannot be the following combination: GB or ZZ.

How do I express that in开发者_开发百科 a regular expression?


Negative lookbehind is the best fit for this.

[A-GZ]{2}(?<!GB)(?<!ZZ)

Explanation:

[A-GZ]{2} matches exactly two characters, both of which must be A-G or Z.
(?<!GB) only matches if the previous two characters matched were not GB.
(?<!ZZ) only matches if the previous two characters matched were not ZZ.

The negative lookbehind, like all lookahead and lookbehind operations, is zero width, meaning it does not change the cursor position. This is why you can string together two in a row as I did. I like this better than |, because it makes it clear the two cases that are not allowed. And doing it twice should have about the same runtime effect as the | operator in a single lookbehind.


^([A-F][A-GZ]|G[AC-GZ]|Z[A-G]).*


^([A-F][A-GZ]|G[AC-GZ]|Z[A-G])

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜