Regular Expression to match PO Box address

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 ...
}

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());

Tags:

Java

Regex