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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Negative lookbehind is the best fit for this.
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.