// pattern 20xx/xx/xx, e.g. 2012/2/22
String Regex_Date_1 = "20\\d\\d/\\d{1,2}/\\d{1,2}";
String cell = "from 2011/7/31 to 2011/8/15 15:10-17:40,18:30-21:00";
System.out.println(cell);
System.out.println("--- a ---");
System.out.println( cell.matches(Regex_Date_1) );
System.out.println("--- b ---");
Pattern p = Pattern.compile(Regex_Date_1);
Matcher m = p.matcher(cell);
while(m.find()){
System.out.println( m.group(0) );
}
results:
from 2011/7/31 to 2011/8/15 15:10-17:40,18:30-21:00
--- a ---
false
--- b ---
2011/7/31
2011/8/15
Why string.matches return false? but pattern.matches can get matches?
Because
String#matcheswill returntrue“if, and only if, this string matches the given regular expression”. You can check the documentation here : String#matchesHowever
Matcher#findwill returntrue” if, and only if, a subsequence of the input sequence matches this matcher’s pattern”. The documentation is available here : Matcher#find.So to sum up –
String#matchesreturns true if the whole string is matched by the regex andMatcher#findreturns true if some subsequence of the String can be matched by the regex.