Reputation: 3484
I'm using this regular expression to catch "PO Box" strings. This seems to work when I test it online but the javacode below is printing false. What mistake am I making?
/^\s*((P(OST)?.?\s*(O(FF(ICE)?)?)?.?\s+(B(IN|OX))?)|B(IN|OX))/i
String to test - PO Box 1234
String spattern = "/^\\s*((P(OST)?.?\\s*(O(FF(ICE)?)?)?.?\\s+(B(IN|OX))?)|B(IN|OX))/i";
String regex = "PO Box 1234";
Pattern pattern = Pattern.compile(spattern);
System.out.println(pattern.matcher(regex).matches());
I've tested the expression online at http://regex101.com/ and it says there is match for the test string
Upvotes: 8
Views: 8033
Reputation: 11
Regex to check the PO box address, specifically for USA addresses:
This works perfectly for me.
Java:
static final String thePattern = "(?i)([\w\s*\W](P(OST)?.?\s((O(FF(ICE)?)?).?\s*(B(IN|OX|.?)))+))[\w\s*\W]|(COMMUNITY\s)?POST(AL)?\s*(OFF(ICE)?(\s*(BOX|BOZ|BX))?|(BOX|BX))|(^\s*(BOXOC|P\.?0\.?))";
Samples which the above regex will detect:
Post Office Bin : Valid
P O Box DesMoines1000 : Valid
1316 PO BOX Benjamin Street : Valid
P Browny House : Invalid
Community P Box : Invalid
P Boxting : Invalid
P Binter : Invalid
JavaScript:
var regex = /^([\w\s*\W](P(OST)?.?\s((O(FF(ICE)?)?).?\s*(B(IN|OX|.?)))+))[\w\s*\W]|(COMMUNITY\s)?POST(AL)?\s*(OFF(ICE)?(\s*(BOX|BOZ|BX))?|(BOX|BX))|(^\s*(BOXOC|P.?0.?))$/i;
Upvotes: -1
Reputation: 124215
In Java you don't use the form /regex/flags
. Instead you can do something like
Pattern.compile(regex, flags);
So remove /
and /i
and try with
String spattern = "^\\s*((P(OST)?.?\\s*(O(FF(ICE)?)?)?.?\\s+(B(IN|OX))?)|B(IN|OX))";
Pattern pattern = Pattern.compile(spattern, Pattern.CASE_INSENSITIVE);
You can also pass flags directly to regex string. Just add (?i)
at the beginning for case insensitive regex. You can add this flag at any place, depending of scope it should affect. For instance if you place it like this a(?i)a
regex will be able to match aa
and aA
but not Aa
or AA
because flag works from point between first and second a
. Similarly a((?i)a)a
will match aaa
and aAa
but will not match AAa
nor aAA
because (?i)
affects only scope of group 1 (the part in parenthesis). More info at http://www.regular-expressions.info/modifiers.html
Also, the matches
method checks if entire string is matched by regex, not if string contains part that can be matched by regex. Maybe instead of matches
use the find
method like
System.out.println(pattern.matcher(regex).find());
Upvotes: 3
Reputation: 43013
Change your pattern like this:
String spattern = "(?i)^\\s*((P(OST)?.?\\s*(O(FF(ICE)?)?)?.?\\s+(B(IN|OX))?)|B(IN|OX))";
If you know you won't use your pattern often, you can try this instead:
String myInput = ....
if (myInput.matches(spattern)) {
// myInput is a PO BOX ...
} else {
// myInput isn't a PO BOX ...
}
Upvotes: 5