String str = "m222";
Pattern p = Pattern.compile("[0-9]+");//0至9,出现一次或多次
Matcher m = p.matcher(str);
println("m.matches->>"+m.matches());//打印输出
if(m.find()){
println("m.find->>true");
println("m.start->>"+m.start());
println("m.end->>"+m.end());
println("m.child->>"+str.substring(m.start(),m.end()));
} else {
println("m.find->>false");
}
上面代码中用Pattern做了一个正则表达式p,然后用p去匹配str,最后得到匹配结果对象m。
m常用的方法有find()和matches()。这两个方法用于获取匹配结果,按照上方的代码输出结果会是这样
m.matches->>false
m.find->>true
m.start->>1
m.end->>4
m.child->>222
这时会有点疑惑,为什么matches方法返回了false,而find返回了true呢?
因为matches方法的匹配机制是针对整个字符串的,按照上面代码给出的正则表达式,如果想要通过matches方法返回true,则str必须全部是数字。
而find方法则不同,它属于搜索匹配。比如传入str="222m333",find方法会将这个字符串拆成若干个子字符串,只要有一个或多个子字符串符合正则表达式,则返回true。并且find方法还有类似于Map集合中next方法的功能。例如str=“222m333”时,第一次调用find方法,此时Matcher对象m的start值会为0、end值会为3。而再次调用时会start值会变成4、end值变成7。如果我们再调用一次find,就会直接返回false了。
这里贴一下find方法的源码
/**
* Attempts to find the next subsequence of the input sequence that matches
* the pattern.
*
* <p> 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.
*
* <p> If the match succeeds then more information can be obtained via the
* {@code start}, {@code end}, and {@code group} methods. </p>
*
* @return {@code true} if, and only if, a subsequence of the input
* sequence matches this matcher's pattern
*/
public boolean find() {
int nextSearchIndex = last;
if (nextSearchIndex == first)
nextSearchIndex++;
// If next search starts before region, start it at region
if (nextSearchIndex < from)
nextSearchIndex = from;
// If next search starts beyond region then it fails
if (nextSearchIndex > to) {
for (int i = 0; i < groups.length; i++)
groups[i] = -1;
return false;
}
return search(nextSearchIndex);
}