1.1 前言
如果在一个项目中需要验证输入的文本是不是电话号码格式,我们应该怎么办呢?
不使用正则表达式的话,就要先判断输入的文本长度是不是 11,再判断第一个数字是不是数字 1,再判断第二个数字是不是 3,4,5,6,7,8,9,最后判断剩下的字符是不是数字,就像这样:
public class Test {
public static void main(String[] args) {
System.out.println("请输入手机号码:");
Scanner scanner = new Scanner(System.in);
String inputStr = scanner.next();
if (inputStr.length() == 11) {
if (inputStr.charAt(0) == '1') {
int secondNum = (int)inputStr.charAt(1);
if (secondNum - 48 >= 3) {
for (int i = 2; i < inputStr.length(); i++) {
// 运用 Character 类的 isDigit 方法来判断是否为数字字符
if (Character.isDigit(inputStr.charAt(i))) {
if (i == inputStr.length() - 1)
System.out.println("你输入的是手机号码");
}
else {
System.err.println("手机号码输入错误");
}
}
}
else {
System.err.println("手机号码输入错误");
}
}
else {
System.err.println("手机号码输入错误");
}
}
else {
System.err.println("手机号码输入错误");
}
}
}
虽然这样也可以,但用正则表达式来解决的话,代码量明显减少
public class Test2 {
public static void main(String[] args) {
System.out.println("请输入手机号码:");
Scanner scanner = new Scanner(System.in);
String inputStr = scanner.next();
// 括号内的内容就是正则表达式
Pattern pattern = Pattern.compile("1[3-9]\\d{9}");
Matcher matcher = pattern.matcher(inputStr);
boolean isPhoneNum = matcher.matches();
if (isPhoneNum == false) {
System.err.println("手机号码输入错误");
}
else {
System.out.println("输入的是手机号码");
}
}
}
同样是查找和匹配字符,在正则表达式中只需要使用几个特殊字符([3-9],\d,{9})就可以完成。而这些特殊字符就是元字符。
1.2 元字符的分类
- 所以 [3-9] 表示这个字符在 3 到 9 的范围内, \d{9} 表示 9 个数字字符;
- 元字符 \w 能匹配所有的数字、字母和下划线但不包括其他特殊符号;