java正则表达式判断电话号码是否正确
1. while循环
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class demothere {
static String regex="^[1][3-8][0-9]{9}$";
public static void main(String[] args) {
String answer="yes";
while(answer.equalsIgnoreCase("yes")) {
System.out.print("输入电话号码:");
Scanner phone=new Scanner(System.in);
String phones=phone.next();
Pattern pattern=Pattern.compile(regex);
Matcher matcher=pattern.matcher(phones);
boolean bool=matcher.matches();
if(bool) {
System.out.println("电话号码格式正确");
}else {
System.out.print("格式错误,请输入正确的电话号码");
}
System.out.print("是否继续输入(yes/no):");
answer=phone.next();
}
System.out.println("输入结束");
}
}
2.while 循环判断
public class demothere {
static String regex="^[1][3-8][0-9]{9}$";
public static void main(String[] args) {
do {
System.out.print("输入电话号码:");
Scanner phone=new Scanner(System.in);
String phones=phone.next();
Pattern pattern=Pattern.compile(regex);
Matcher matcher=pattern.matcher(phones);
boolean bool=matcher.matches();
if(bool) {
System.out.println("电话号码格式正确");
}else {
System.out.print("格式错误,请输入正确的电话号码");
}
System.out.print("是否继续输入(yes/no):");
answer=phone.next();
}
while(answer.equalsIgnoreCase("yes"));
System.out.println("输入结束");
}
}