需求:
校验手机号码,邮箱,电话号码
实现代码:
package apilambda.d6_regex;
import java.util.Scanner;
public class RegexTest2 {
public static void main(String[] args) {
//需求:校验手机号码,邮箱,电话号码
//验证手机号
checkPhone();
//验证邮箱
checkEmail();
//验证电话号码
checkTel();
}
//验证电话号码
public static void checkTel(){
Scanner sc=new Scanner(System.in);
while (true) {
System.out.println("请输入您的电话号码:");
String tel=sc.next();
//校验手机号(正则表达式)
if (tel.matches("0\\d{2,6}-?\\d{5,20}")) {
System.out.println("验证正确!!!");
return;
}else {
System.out.println("验证错误!!!");
}
}
}
//验证邮箱
public static void checkEmail(){
Scanner sc=new Scanner(System.in);
while (true) {
System.out.println("请输入您的邮箱:");
String email=sc.next();
//校验手机号(正则表达式)
if (email.matches("\\w{1,30}@[a-zA-Z0-9]{2,20}(\\.[a-zA-Z0-9]{2,20}){1,2}")) {
System.out.println("验证正确!!!");
return;
}else {
System.out.println("验证错误!!!");
}
}
}
//验证手机号
public static void checkPhone(){
Scanner sc=new Scanner(System.in);
while (true) {
System.out.println("请输入您的手机号:");
String phone=sc.next();
//校验手机号(正则表达式)
if (phone.matches("1[3-9]\\d{9}")) {
System.out.println("验证正确!!!");
return;
}else {
System.out.println("验证错误!!!");
}
}
}
}
运行截图: