正则表达式 Matcher类find() reset()
本帖最后由 ljblxx 于 2013-09-22 22:24:59 编辑
public class test{
public static void main(String[] args){
Pattern p = Pattern.compile("\\d{3,5}");
String s = "123-34345-234-00";
Matcher m = p.matcher(s);
System.out.println(m.matches());
System.out.println(m.find());
System.out.println(m.find());
System.out.println(m.find());
System.out.println(m.find());
}
}
结果输出:
false
true
true
false
false
本人认为的结果:
false
true
true
false
true
另外 一个问题 就是m.reset()的作用是? 看API 那里不是很懂。
分享到:
------解决方案--------------------
matches(),find()都会影响标记,而reset()可以重置这些标记!
另外,这些标记不会循环,所以第四次已经消耗完所有字符,不可能再有true了
------解决方案--------------------
A matcher is created from a pattern by invoking the pattern's matcher method
每一次matcher方法运行的时候,便会产生一个matcher
The explicit state of a matcher includes the start and end indices of the most recent successful match.
matcher的状态包括关于最近匹配的start和end
稍微改下程序你就懂了,reset把matcher的状态清空了
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class test2{
public static void main(String[] args){
Pattern p = Pattern.compile("\\d{3,5}");
String s = "123-34345-234-00";
Matcher m = p.matcher(s);
System.out.println(m.matches());
System.out.println(m.find()+"start at:"+m.start()+" end at:"+m.end());
System.out.println(m.find()+"start at:"+m.start()+" end at:"+m.end());
// System.out.println(m.find()+"start at:"+m.start()+" end at:"+m.end());
// System.out.println(m.find()+"start at:"+m.start()+" end at:"+m.end());
m.reset();
System.out.println(m.find()+"start at:"+m.start()+" end at:"+m.end());
System.out.println(m.find()+"start at:"+m.start()+" end at:"+m.end());
}
}