正则表达式
regex:多用于验证正确或者错误
\\w: [a-zA-Z_0-9] 需要熟记一些常用的\\其他了解
\d 代表数字[0-9]
数量词: ? * + {n} {n, } {n, m}
其他几个常用的符号:(?i)忽略大小写 、 或:| 、 分组:()
例:email.matches 是生成规定的字符串长度 判断是否正确
public static void checkEmail(){
while (true) {
System.out.println("请您输入邮箱:");
String email = new Scanner(System.in).next();
// 4324234@qq.com
// dlei0009@163.com
// xulei2@pci.com.cn
if(email.matches("\\w{2,30}@\\w{2,20}(\\.\\w{2,10}){1,2}")) {
System.out.println("恭喜您,邮箱正确!");
break;
}else {
System.out.println("您输入的邮箱格式有毛病,请重新输入!");
}
}
封装正择表达式(爬取的规则)
Pattern pattern = Pattern.compile(表达式);//获取规则
Matcher matcher = pattern.matcher(表达式);//将规则内容与爬取建立联系
死循环匹配对象
matcher.find() 输出:matcher.group()
public static void main(String[] args) {
// 目标:了解使用正则表达式去文本中爬取想要的信息。
String data = "学习Java,\n" +
"电话:18512516758,18512508907\n" +
"或者联系邮箱: boniu@itcast.cn\n" +
"座机电话:01036517895,010-98951256\n" +
"邮箱:bozai@itcast.cn,\n" +
"邮箱2:dlei0009@163.com,\n" +
"热线电话:400-618-9090 ,400-618-4000,\n" +
"4006184000,4006189090\n";
// 1、创建一个匹配规则对象,封装正则表达式(爬取的规则)
String regex = "(1[3-9]\\d{9})|((0[1-9]\\d{1,4})-?[1-9]\\d{4,9})|(\\w{2,30}@\\w{2,20}(\\.\\w{2,10}){1,2})" +
"|(400-?[1-9]\\d{2,5}-?[1-9]\\d{2,5})";
Pattern pattern = Pattern.compile(regex);
// 2、把内容和爬取规则建立联系,得到一个匹配器对象
Matcher matcher = pattern.matcher(data);
while (matcher.find()){
System.out.println(matcher.group());
}