Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression to match PO Box address

Tags:

java

regex

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

like image 826
RKodakandla Avatar asked Mar 04 '14 14:03

RKodakandla


2 Answers

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 ...
}
like image 88
Stephan Avatar answered Oct 24 '22 10:10

Stephan


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());
like image 30
Pshemo Avatar answered Oct 24 '22 10:10

Pshemo