否定环视无效时,否定整个正则表达式模式 [英] negate the whole regex pattern when negative lookaround doesn't work

查看:94
本文介绍了否定环视无效时,否定整个正则表达式模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与P.O匹配的正则表达式.给定地址上的BOX-/p\.? *o\.? *box/i.但是最近我的要求更改为符合P.O.盒子.换句话说,该地址在P.O.时有效.找不到BOX.我正在尝试取消该模式,以使其与没有邮政信箱的地址匹配.通过使用negative lookahead进行包装,到目前为止,这是我想出的内容:/.*(?!p\.? *o\.? *box).*/i,但现在无法正常工作: https://regex101.com/r/oN1jZ8/1

I had a regex that matches a P.O. BOX on a given address - /p\.? *o\.? *box/i. But recently my requirement changes to NOT match the P.O. BOX. In other words, the address is valid when P.O. BOX is not found. I was trying to negate that pattern so it matches an address that has no P.O. BOX by using negative lookahead, this is what I came up with so far: /.*(?!p\.? *o\.? *box).*/i, but it is not working right now: https://regex101.com/r/oN1jZ8/1

例如,我尝试匹配以下内容:

For example, I try to match the following:

  • 这是有效地址

但不是以下内容:

  • 这是无效的地址,因为它包含 P.O. BOX
  • 邮政信箱出现,因此无效
  • this is a invalid address because it contains a P.O. BOX
  • po box shows up so it is invalid

我知道一些类似的帖子,例如:

I am aware of a few similar posts, such as:

  • How to negate the whole regex?
  • Regular Expressions and negating a whole character group
  • Regex to negate the whole word?

negative lookaround就是其中的解决方案.

where pretty much the negative lookaround is the solution.

推荐答案

您应该使用此否定前瞻:

You should use this negative lookahead:

^(?!.*p\.? *o\.? *box).*

区别在于在前瞻模式中使用起始锚^.*.

Difference is use of start anchor ^ and use of .* inside the lookahead pattern.

更新了RegEx演示

这篇关于否定环视无效时,否定整个正则表达式模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆