简体   繁体   English

正则表达式。 开头且不等于

[英]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. 前两个字符必须由AG或Z组成,但不能为以下组合:GB或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. [A-GZ]{2}正好匹配两个字符,两个字符都必须为AG或Z。
(?<!GB) only matches if the previous two characters matched were not GB. (?<!GB)仅在匹配的前两个字符不是GB时才匹配。
(?<!ZZ) only matches if the previous two characters matched were not ZZ. (?<!ZZ)仅在匹配的前两个字符不是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])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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