negate the whole regex pattern when negative lookaround doesn't work

為{幸葍}努か 提交于 2019-12-11 13:22:38

问题


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:

  • this is a valid address

But not the following:

  • 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?

where pretty much the negative lookaround is the solution.


回答1:


You should use this negative lookahead:

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

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

Updated RegEx Demo



来源:https://stackoverflow.com/questions/35438324/negate-the-whole-regex-pattern-when-negative-lookaround-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!