需求:一个验证手机手机号码合法性的正则表达式,需要在输入过程逐位匹配,也就是说遇到不匹配的字符马上终止,如:当输入手机号码,第一位输入1,OK。第二位输入2则终止匹配,返回不合法
java.util.regex.Matcher.hitEnd()方法描述:
<p>Returns true if the end of input was hit by the search engine in
the last match operation performed by this matcher.
<p>When this method returns true, then it is possible that more input
would have changed the result of the last search.
public static void main(String[] args) {
String regex = "^(13|15|18)\\d{9}$";
Pattern p = Pattern.compile(regex);
String[] testArr = {
"138",
"112",
"138000000000000",
"13800138000"
};
for (String string : testArr) {
testMatch(p,string);
}
}
private static void testMatch(Pattern p, String string) {
Matcher matcher = p.matcher(string);
System.out.println("string:" + string + "---matches:"
+ matcher.matches() + "---hitEnd:" + matcher.hitEnd());
}
java.util.regex.Matcher.hitEnd()方法描述:
<p>Returns true if the end of input was hit by the search engine in
the last match operation performed by this matcher.
<p>When this method returns true, then it is possible that more input
would have changed the result of the last search.