okorng okorng - 1 year ago 75
Javascript Question

How to combine a negative and positive regex?

I think it's possible to define a single RegExp string that will check two things - whether the user is NOT trying to enter a post office box and whether the user is using only valid characters. The two separate RegExp are as follows:

PO BOX Validation :


User Can enter these Char Only:

^[a-z|A-Z|0-9 _&'/#]*$

When I try to simply concatenate the two regex's together with a vertical 'OR' character '|', it doesn't achieve the desired result. Is this even possible? Can a single regex achieve both validations?

Answer Source

If you use your own regexps to combine, you should notice that the first regex is actually a pattern with a kind of a poorly formed tempered greedy token.

It seems you wanted something like

/^(?!.*\b[Pp]([Oo0][Ss][Tt])?\.*\s*[Oo0]([Ff][Ff]([Ii][Cc][Ee])?)?\.*\s*([Bb][Oo0][Xx])\d*\s*\b)[a-zA-Z0-9 _&'\/#]*$/

See the regex demo

Note that [a-z|A-Z|0-9 _&'/#] should not contain |, as they are treated as literal pipe symbols while you most probably meant to use them as OR operators. They are OR operators inside parentheses, but not inside a character class.

Pattern details:

  • ^ - start of string
  • (?!.*\b[Pp]([Oo0][Ss][Tt])?\.*\s*[Oo0]([Ff][Ff]([Ii][Cc][Ee])?)?\.*\s*([Bb][Oo0][Xx])\d*\s*\b) - a negative lookahead that fails the match if the pattern inside it is matched
  • [a-zA-Z0-9 _&'/#]* - zero or more allowed chars
  • $ - end of string.

Since [a-zA-Z0-9_] = \w, you can write the same as

/^(?!.*\b[Pp]([Oo0][Ss][Tt])?\.*\s*[Oo0]([Ff][Ff]([Ii][Cc][Ee])?)?\.*\s*([Bb][Oo0][Xx])\d*\s*\b)[\w &'\/#]*$/
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download