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:

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

where pretty much the negative lookaround is the solution.

Community
  • 1
  • 1
Liang Zhou
  • 2,055
  • 19
  • 20

1 Answers1

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

anubhava
  • 761,203
  • 64
  • 569
  • 643