0

I have a function from another thread that helps to detect POBoxes, but it doesn't quite work as intended.

function isPOBox(v){
    var r = new RegExp('[PDO.]*\\s?B(ox)?.*\\d+', 'i');
    return v.match(r);
}

If I have the value 'Lvl 1 TowerB, 999 C G Road' it incorrectly picks it up as a PObox.
As you can see, there's no P in the above.

How would I go about editing the regex to be more specific around POBoxes?

I have set up a demo Fiddle here: http://jsfiddle.net/xCQwM/

ahren
  • 16,803
  • 5
  • 50
  • 70

2 Answers2

2

If you look at the actual match:

> "Lvl 1 TowerB, 999 C G Road".match(new RegExp('[PDO.]*\\s?B(ox)?.*\\d+',"i"))
[ 'B, 999',
  undefined,
  index: 11,
  input: 'Lvl 1 TowerB, 999 C G Road' ]

That is a match because:

  • [PDO.]\* indicates that the first part of the match is optional
  • \\s? is optional
  • (ox)? is optional
  • .* is optional

One set of strings that will match your regex is:

"B" followed by any number of characters followed by a digit

In your example, the match looks like

"B" matches "B"
"," matches ".*"
"999" matches "\\d+"

You need to give more details regarding what you expect a P.O. Box to look like in order for us to give a better regex

SheetJS
  • 22,470
  • 12
  • 65
  • 75
  • Thanks for your time and help on this - I've just been doing some more searching and found a regex that works a bit better. `new RegExp('\\b[p]*(ost)*\\.*\\s*[o|0]*(ffice)*\\.*\\s*b[o|0]x\\b', 'i');` – ahren Jun 28 '13 at 14:08
0

The answer to your question, as you have currently worded it, is to replace [PDO.]* with [PDO.]+ so it matches at least one char. You might want to use ([PDO]\\.){2} though.

I'm thinking something like this might be better:

([PDO]\\.){2}\\s?B(ox|\\.)\\s?\\d+
ctn
  • 2,887
  • 13
  • 23
  • Thanks for your time and help on this - I've just been doing some more searching and found a regex that works a bit better. `new RegExp('\\b[p]*(ost)*\\.*\\s*[o|0]*(ffice)*\\.*\\s*b[o|0]x\\b', 'i');` – ahren Jun 28 '13 at 14:08