正则表达式
匹配规则

校验案例
package com.test;
import java.util.Scanner;
public class Regex {
public static void main(String[] args) {
RegexPhone();
RegexEmail();
RegexTel();
}
public static void RegexTel(){
System.out.println("请输入座机号码:");
while(true) {
Scanner sc = new Scanner(System.in);
String phone = sc.next();
if (phone.matches("(\\d{2,3}-){1,2}\\d{3,8}")) {
// 国家 地区 2-3位数字
System.out.println("格式正确!");
break;
} else {
System.out.println("格式有误!请重新输入!");
}
}
}
public static void RegexEmail(){
System.out.println("请输入邮箱账号:");
while(true) {
Scanner sc = new Scanner(System.in);
String phone = sc.next();
if (phone.matches("\\w{1,30}@[a-zA-Z0-9]{2,20}(\\.[a-zA-Z]{2,20}){1,2}")) {
// 账号 英文数字下划线 至少1位但不超过30位
// 域名 英文数字 至少2位但不超过20位
// 域名性质 至少出现1次但不超过出现2次
System.out.println("格式正确!");
break;
} else {
System.out.println("格式有误!请重新输入!");
}
}
}
public static void RegexPhone(){
System.out.println("请输入手机号码:");
while(true) {
Scanner sc = new Scanner(System.in);
String phone = sc.next();
if (phone.matches("1[3-9]\\d{9}")) { // 首位为1 第二位3-9 其余9位为都是整数 ,共11位数字
System.out.println("格式正确!");
break;
} else {
System.out.println("格式有误!请重新输入!");
}
}
}
}
爬取案例
package com.test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
String text ="地址:重庆 南岸 重庆邮电大学\n" +
"电话:86-023-62461003\n" +
"邮件:bangongshi@cqupt.edu.cn\n" +
"传真:86-023-62461882\n";
/**
* 定义爬取规则
*/
String regexPhone = "(1[3-9]\\d{9})|"+ "((\\d{2,3}-){1,2}\\d{3,8})";
String regexEmail = "\\w{1,30}@[a-zA-Z0-9]{2,20}(\\.[a-zA-Z]{2,20}){1,2}";
/**
* 将爬取规则编译成匹配对象
*/
Pattern patternPhone = Pattern.compile(regexPhone);
Pattern patternEmail = Pattern.compile(regexEmail);
/**
* 获取内容匹配器对象
*/
Matcher matcherPhone = patternPhone.matcher(text);
Matcher matcherEmail = patternEmail.matcher(text);
/**
* 开始匹配爬取
*/
System.out.println("爬取手机号");
while(matcherPhone.find()){
String phone = matcherPhone.group();
System.out.println(phone);
}
System.out.println("爬取邮箱");
while(matcherEmail.find()){
String email = matcherEmail.group();
System.out.println(email);
}
}
}
