简体   繁体   中英

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 AG, 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 AG 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]).*

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM