问题
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