正则表达式
就是由一些特定的字符组成,代表是一个规则
校验格式正确
校验内容
Pattern、Matcher
public class Test4 {
public static void main(String[] args) {
method1();
}
public static void method1() {
String data = " 来黑马程序员学习Java,\n" +
"电话: 1866668888,18699997777\n" +
"或者联系邮箱: boniu@itcast.cn,n" +
"市机电话: 01036517895,810-98951256\n" +
"邮箱: bozai@itcast.cn,\n" +
"邮箱: dlei0009@163.com,n" +
"邮箱: dlei.0009@163.com,n" +
"热线电话: 400-618-9090 ,400-618-4000,4006184000,4006189090";
// 手机 电话 邮箱 400
String regex = "([1][3-9]\\d{9})|(0\\d{2,7}-?\\d{4,19})|((\\w|[.]){2,}@\\w{2,20}(\\.\\w{2,10}){1,2})" +
"|(400-?\\d{3,7}-?\\d{3,7})";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(data);
while (matcher.find()){
String rs = matcher.group();
System.out.println(rs);
}
}
}
用于搜索替换、分割内容
replaceAll、split 以及 \\组号 $组号调用
public class Test5 {
public static void main(String[] args) {
// 1、public String replaceAll(String regex ,String newStr): 按照正则表达式区配的内容进行替换
// 需求1:请把 古力娜扎8888迪丽热巴999aa5566马尔扎fbbfsfs42425卡尔扎巴,中网的非中文字符营换成"-"
String data1 = "古力娜扎8888迪丽热巴999aa5566马尔扎fbbfsfs42425卡尔扎巴";
System.out.println(data1.replaceAll("\\w+", "-"));
// 需求2(拓展):某语音系统,收到一个口吃的人说的“我我我喜欢编编编编编编编编编编编编程程程! ",需要优化成"我喜欢编程!"。
String data0 = "我我我喜欢编编编编编编编编编编编编程程程!";
// (.)一组:.匹配任意字符的。*
// \\1 :为这个组声明一个组号:1号
// +: 声明各须是重复的字
// $1可以去到第1组代表的服个重复的字
System.out.println(data0.replaceAll("(.)\\1+", "$1"));
// 2、public String[] spit(String regex):按照正则表达式区配的内容进行分字符,反同一个字符串数组
// 需求1:请把 古力娜扎i8888迪热巴9995566马尔扎哈fbbfsfs42425卡尔扎巴,中的人名获取出来
String data2 = "古力娜扎i8888迪热巴9995566马尔扎哈fbbfsfs42425卡尔扎巴";
String[] res = data2.split("\\w+");
System.out.println(Arrays.toString(res));
}
}