当否定环视不起作用时否定整个正则表达式模式
negate the whole regex pattern when negative lookaround doesn't work
我有一个匹配 P.O 的正则表达式。给定地址上的 BOX - /p\.? *o\.? *box/i
。但最近我的要求更改为 NOT 匹配 P.O。盒子。也就是说,地址在P.O时有效。未找到 BOX。我试图否定该模式,以便它匹配没有 P.O 的地址。 BOX 通过使用 negative lookahead
,这是我到目前为止想出的:/.*(?!p\.? *o\.? *box).*/i
,但它现在不起作用:https://regex101.com/r/oN1jZ8/1
比如我尝试匹配如下:
- 这是一个有效的地址
但不是以下内容:
- 这是一个无效地址,因为它包含 P.O。盒子
- 邮政信箱出现所以无效
我知道一些类似的帖子,例如:
- How to negate the whole regex?
- Regular Expressions and negating a whole character group
- Regex to negate the whole word?
几乎 negative lookaround
就是解决方案。
你应该使用这个负前瞻:
^(?!.*p\.? *o\.? *box).*
不同之处在于在前瞻模式中使用起始锚点 ^
和使用 .*
。
我有一个匹配 P.O 的正则表达式。给定地址上的 BOX - /p\.? *o\.? *box/i
。但最近我的要求更改为 NOT 匹配 P.O。盒子。也就是说,地址在P.O时有效。未找到 BOX。我试图否定该模式,以便它匹配没有 P.O 的地址。 BOX 通过使用 negative lookahead
,这是我到目前为止想出的:/.*(?!p\.? *o\.? *box).*/i
,但它现在不起作用:https://regex101.com/r/oN1jZ8/1
比如我尝试匹配如下:
- 这是一个有效的地址
但不是以下内容:
- 这是一个无效地址,因为它包含 P.O。盒子
- 邮政信箱出现所以无效
我知道一些类似的帖子,例如:
- How to negate the whole regex?
- Regular Expressions and negating a whole character group
- Regex to negate the whole word?
几乎 negative lookaround
就是解决方案。
你应该使用这个负前瞻:
^(?!.*p\.? *o\.? *box).*
不同之处在于在前瞻模式中使用起始锚点 ^
和使用 .*
。