I have the following regex for postal address validation in my angular app.
const regx = '\\b([p]*(ost)*\\.*\\s*[o|0]*(ffice)*\\.*\\s*b[o|0]x)\\b'
I only wanted this regex to pass for
Match list:
- P.O.Box
- pobox
- post office box
- 1234 post office box street
- 123 postal office box
but it also matches for
Do not match list:
- box
- BOX
- poor box
etc.,
How can I tighten this regex so it does not match the "Do not match list"? Also, I wanted my regex to be upgraded for things like postal office box or post office bin etc. Any inputs?
CodePudding user response:
With your shown samples please try following regex. Here is the Online Demo for used regex.
^(?:[0-9]*\s*[pP](?:\.O\.|o)(?:st(?:al)?\soffice\s)*[bB]ox(?:\sstreet)?)$
Explanation: Adding detailed explanation for above regex.
^(?: ##Starting 1 non-capturing group from starting of the value.
[0-9]*\s* ##Matching 0 or more digits followed by 0 or more spaces.
[pP] ##Matching p OR P here.
(?:\.O\.|o) ##In a non-capturing group matching .O. OR o here.
(?:st(?:al)?\soffice\s)* ##In a non-capturing group matching st followed by spaces followed by office followed by spaces and keeping this non-capturing group Optional.
[bB]ox ##Matching b OR B followed by ox here.
(?:\sstreet)? ##In a non-capturing group matching space street and keep this optional.
)$ ##Closing non-capturing group at the end of the value here.
CodePudding user response:
Here is another variant that should work for you:
/^(?:\d \s*)?p\.?o\.?(?:st(?:al)?)?(?:\s office)?\s*b(?:ox|in)\b.*/gmi
Since we we are using ignore case modifier here so we can use all lower case letters in our regex.