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
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With