Why does this Pattern not match the port in my URL?
public class PatternTest {
private Pattern PORT_STRING_PATTERN = Pattern.compile(":\\d+/");
private boolean hasPort(String url) {
return PORT_STRING_PATTERN.matcher(url).matches();
}
@Test
public void testUrlHasPort() {
assertTrue("does not have port", hasPort("http://www.google.com:80/"));
}
}
If I change the pattern to Pattern.compile("^.+:\\d+/")
it does match. Why do I need the ^.+
?
The problem is that you're using Matcher.matches()
, which is documented as:
Attempts to match the entire region against the pattern.
You don't want to match the entire region - you just want to find a match within the region.
I think you probably want to be calling find()
instead:
Attempts to find the next subsequence of the input sequence that matches the pattern.
This method starts at the beginning of this matcher's region, or, if a previous invocation of the method was successful and the matcher has not since been reset, at the first character not matched by the previous match.
See more on this question at Stackoverflow