- 第一题:校验给定的字符串是否为纯数字
如果我们用String中的其他各种方法去写,不管有多么优化的写法,大概结果就是这样的。
/**
* 校验是否为纯数字
* @param str
* @return如果为纯数字,返回true
*/
public static boolean isNumber(String str) {
if(!isEmpty(str)) {
return false;
}
char []chars = str.toCharArray();
for(char num:chars) {
if(!Character.isDigit(num)) {
return false;
}
}
return true;
}
如果换做正则表达式来写:
/**
* 校验是否为纯数字
* @param str
* @return如果为纯数字,返回true
*/
public static boolean isNumber(String str) {
if(!isEmpty(str)) {
return false;
}
//正则表达式 牛逼的大写校验货
return (str.matches("\\d+"));//\d表示校验数字0~9
}
2. 判断是否是正确的电子邮件
如果用普通方法写,看起来是这样的:
/**
* @param str
* @return
*/
public static boolean isEmail(String str) {
if(!isEmpty(str)) {
return false;
}
int atIndex = str.indexOf("@");
int dotIndex = str.indexOf(".");
if(atIndex == -1 || atIndex == 0 || atIndex == str.length() - 1) {
return false;
}
if(dotIndex == -1 || dotIndex == 0 || dotIndex == str.length() - 1) {
return false;
}
//判断@和点之间的位置
if(atIndex >= dotIndex - 1) {
return false;
}
//判断没有两个@
if(atIndex != str.lastIndexOf("@")) {
return false;
}
//判断.的个数
String []strs = str.split("\\.");//加上反斜杠将.转译为普通字符
System.out.println(strs.length);
if(strs.length != 2 && strs.length != 3) {
return false;
}
return true;
}
若换为正则表达式,应该是这样的:
public static boolean isEmail(String str) {
return (str.matches("\\w+@\\w+(\\.\\w+){1,2}"));
}//不完善,只当练手
上面几十行的代码,下边也就寥寥几行就搞定了。
3. 总结一些常用的正则表达式校验,以后或许会用的到哦
1. 身份证号码校验
public static boolean IsIDcard(String str) {
String regex = "(^\\d{18}$)|(^\\d{15}$)";
return str.matches(regex);
}
- 手机号码验证
public static boolean IsTelNumber(String str) {
return str.matches("1[3578]\\d{9}");
}