JAVA 使用正则表达式判断邮箱地址,手机号码是否符合格式
检测邮箱地址
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexDemo {
public static void main(String[] args) {
// Pattern类 正则表达式的编译表示。
Pattern pattern = Pattern.compile("^[a-zA-Z0-9_!#$%&'*+/=?`{|}~^.-]+@[a-zA-Z0-9.-]+$");
String[] emails = {"shiyanlou@shiyanlou.com", "shiyanlou"};
for (String email :
emails) {
//Matcher 通过解释Pattern对字符序列执行匹配操作的引擎
Matcher matcher = pattern.matcher(email);
System.out.println(email + "匹配结果:" + matcher.matches());
}
}
}
编译运行结果
shiyanlou@shiyanlou.com匹配结果:true
shiyanlou匹配结果:false
检测电话号码
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexTest {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("^1([34578])\\d{9}$");
Scanner in = new Scanner(System.in);
String phone = in.nextLine();
Matcher matcher = pattern.matcher(phone);
System.out.println(matcher.matches());
}
}
编译运行结果
输入:
13408199578
输出:
true