需求:对字符串中的多个手机号进行截取
1) 使用正则表达式从字符串中提取数字
2) 检查手机号的有效性(并不十分准确)
import cn.com.sawl.RegularUtils;
import java.util.Arrays;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args){
String content = "17600000001,17600000002/17600000003.176000,176,122";
//正则表达式,用于匹配非数字串,+号用于匹配出多个非数字串
String regEx="[^0-9]+";
Pattern pattern = Pattern.compile(regEx);
//用定义好的正则表达式拆分字符串,把字符串中的数字留出来
String[] tels = pattern.split(content);
System.out.println(Arrays.toString(tels));
for(String tel : tels){
if (!RegularUtils.isMobile(tel)) {
//手机号码有误
System.out.println("手机号码有误 --> " + tel);
continue;
}else{
System.out.println("手机号码正确 --> " + tel);
}
}
}
}
[17600000001, 17600000002, 17600000003, 176000, 176, 122]
手机号码正确 --> 17600000001
手机号码正确 --> 17600000002
手机号码正确 --> 17600000003
手机号码有误 --> 176000
手机号码有误 --> 176
手机号码有误 --> 122
import org.apache.commons.lang3.StringUtils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @Author ds
* @Date 2020-11-28
*/
public class RegularUtils {
/**
* 手机号验证
*
* @param phone
* @return 验证通过返回true
*/
public static boolean isMobile(String phone) {
if (StringUtils.isEmpty(phone)) {
return false;
}
String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$";
if (phone.length() != 11) {
return false;
} else {
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(phone);
boolean isMatch = m.matches();
return isMatch;
}
}
/**
* 校验邮箱
*/
public static boolean isEmail(String emailStr) {
if (StringUtils.isEmpty(emailStr)) {
return false;
}
String pat = "\\w+@\\w+(\\.\\w{2,3})*\\.\\w{2,3}";
Pattern pattern = Pattern.compile(pat);
return pattern.matcher(emailStr).matches();
}
}
参考:https://www.jianshu.com/p/fff9e5667014
网友评论