I have the following (Java) code:
public class TestBlah {
private static final String PATTERN = ".*\\$\\{[.a-zA-Z0-9]+\\}.*";
public static void main(String[] s) throws IOException {
String st = "foo ${bar}\n";
System.out.println(st.matches(PATTERN));
System.out.println(Pattern.compile(PATTERN).matcher(st).find());
System.exit(0);
}
}
Running this code, the former System.out.println outputs false, while the latter outputs true
Am I not understanding something here?
This is because the
.will not match the new line character. Thus, your String that contains a new line, will not match a string that ends with.*. So, when you callmatches(), it returns false, because the new line doesn’t match.The second one returns true because it finds a match inside the input string. It doesn’t necessarily match the whole string.
From the
Patternjavadocs: