正则表达式。始于且不等于
我有一个需要验证的字符串。
前两个字符必须由 AG 或 Z 组成,但不能是以下组合:GB 或 ZZ。
我如何用正则表达式表达它?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
负向回顾最适合这种情况。
说明:
[A-GZ]{2}
恰好匹配两个字符,两个字符都必须是 AG 或 Z。(? 仅当前面匹配的两个字符不是 GB 时才匹配。
(? 仅当前两个匹配字符不是 ZZ 时才匹配。
与所有前向和后向操作一样,负后向查找的宽度为零,这意味着它不会更改光标位置。这就是为什么你可以像我一样将两个连续串在一起。我比|更喜欢这个,因为它明确了两种不允许的情况。执行两次应该具有与 | 大致相同的运行时效果。操作符在单个lookbehind中。
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.
^([AF][A-GZ]|G[AC-GZ]|Z[AG])
^([A-F][A-GZ]|G[AC-GZ]|Z[A-G])