Java正则表达式逐位匹配

本文介绍了一个用于验证中国大陆手机号码合法性的正则表达式,并通过Java代码演示了如何使用该正则表达式进行逐位匹配,确保输入过程中一旦出现非法字符即刻终止匹配。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需求:一个验证手机手机号码合法性的正则表达式,需要在输入过程逐位匹配,也就是说遇到不匹配的字符马上终止,如:当输入手机号码,第一位输入1,OK。第二位输入2则终止匹配,返回不合法

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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值