I understand Java regular expressions can be accessed from the String‘s matches convenience method, or going the long route and making a Pattern, etc. So, the following code should really print 2 “Yes!” lines to the output. It prints “Yes!” line and “no” line. What am I missing?
import java.util.regex.*;
public class TestRegex {
public static void main(String[] args) {
String pattern = "html";
String input = "somehtml.txt";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(input);
if(m.find()) {
System.out.println("Yes!");
}
else {
System.out.println("no");
}
if(input.matches(pattern)) {
System.out.println("Yes!");
}
else {
System.out.println("no");
}
}
}
Output:
Yes!
no
Java version 1.6 on Win7 64-bit.
C:\Users\Michael Smith>java -version
java version “1.6.0_24”
Java(TM) SE Runtime Environment (build 1.6.0_24-b07)
Java HotSpot(TM) 64-Bit Server VM (build 19.1-b02, mixed mode)
matches()checks for the whole string matching the regular expression.find()only looks for a match somewhere in the string.