
package regex;
public class Demo1 {
public static void main(String[] args) {
//用正则表达式来判断QQ号是否正确(只能是数字,且大于6位小于20位)
System.out.println(check(“123465”));
}
public static boolean check(String q){
return q != null && q.matches("\d{6,20}");
}
}
(案例)
package regex;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
//checkPhone();
checkEmail();
}
//正则表达式检查输入手机号,邮箱
public static void checkEmail(){
Scanner scanner =new Scanner(System.in);
while (true){
System.out.println("请输入邮箱");
String email = scanner.nextLine();
if(email.matches("\\w{1,30}@[a-zA-Z0-9]{2,20}(\\.[a-zA-Z0-9]{2,20}){1,2}")){
System.out.println("输入正确,注册成功");
break;
}else {
System.out.println("格式有误");
}
}
scanner.close();
}
public static void checkPhone(){
Scanner scanner =new Scanner(System.in);
while (true){
System.out.println("请输入手机号码");
String phone = scanner.nextLine();
if(phone.matches("1[3-9]\\d{9}")){
System.out.println("输入正确,注册成功");
break;
}else {
System.out.println("格式有误");
}
}
scanner.close();
}
}
该博客展示了如何利用Java编程中的正则表达式进行输入验证,包括检查QQ号的合法性、邮箱格式以及手机号码格式。通过示例代码解释了如何编写正则表达式以确保输入的QQ号必须为6到20位数字,邮箱需符合标准格式,手机号码需以13到19开头并有10位数字组成。
9万+

被折叠的 条评论
为什么被折叠?



