Java正则-String.matches的坑
初学时遇到的问题及错误用法
我想用String.matches匹配一行之中是否有特定的子串,结果死活出不来,我也在好多在线正则匹配的网上测试了,我正则表达式写的正确。查询了半天才知道,用String.matches匹配的正则,相当于会在正则表达式前后加上^ $,是匹配整个大字符串是否满足正则表达式,而不会匹配到其中满足条件的子串!这个可能会让初学者产生迷惑。仔细阅读相关的api,能看的相关说明。
//我的想法是以下2种都会成功匹配,其实是错误的
//以下2种的正则"abc"相当于"^abc$",所以结果false
boolean a = "abcd".matches("abc"); //结果为 false
boolean b =Pattern.matches("abc", "abcd"); //结果为 false
匹配子串的正确方法
//而这种方法就能成功匹配出abcd中的abc,想要匹配子串 直接使用一次m.find()即可
Pattern p=Pattern.compile("abc");
Matcher m=p.matcher("abcd");
while(m.find()){ //m.find() 为true,再次调用将会寻找下个匹配的子串,没有的话就会返回false,相当于迭代器中的next用法
System.out.println(m.group());//abc
}
//或者改写正则表达式 使其匹配整个字符串
boolean a = "abcd".matches(".*abc.*"); //结果为true
分析 java 中的相关源码如下:
//直接用string进行matches
public boolean matches(String regex) {
return Pattern.matches(regex, this);
}
//等于间接使用了Pattern.matches
public static boolean matches(String regex, CharSequence input) {
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
return m.matches();
}
//等于又间接使用了Matcher.matches,说明的很清楚了 匹配的是(entire region sequence)
/**
* Attempts to match the entire region against the pattern.
*
* <p> If the match succeeds then more information can be obtained via the
* <tt>start</tt>, <tt>end</tt>, and <tt>group</tt> methods. </p>
*
* @return <tt>true</tt> if, and only if, the entire region sequence
* matches this matcher's pattern
*/
public boolean matches() {
return match(from, ENDANCHOR);
}
//想要匹配子串可以使用
/**
* 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
* <tt>start</tt>, <tt>end</tt>, and <tt>group</tt> methods. </p>
*
* @return <tt>true</tt> if, and only if, a subsequence of the input
* sequence matches this matcher's pattern
*/
public boolean find() {
// .....省略源码
}
参考链接:stackoverflow