java正则表达式2 -- 匹配、切割、查找

 1 import java.util.Arrays;
 2 
 3 /*
 4 正则表达式的作用:
 5 
 6 1 匹配
 7 
 8 2 切割
 9 
10 3 替换
11 
12  * */
13 public class Demo1 {
14     public static void main(String[] args) {
15         isPhone("0314-16610306");
16         cutStr1("火      影   忍           者");
17         cutStr2("大家家明天天玩的的的的的开心");
18         replaceSame("大家家明天天玩的的的的的开心");
19     }
20     
21     //匹配固话: 区号-主机号   区号:首位为0,长度为3-4位  主机号:首位不能为0,长度7-8位
22     public static void isPhone(String phone){
23         System.out.println(phone.matches("0\d{2,3}-[1-9]\d{6,7}")?"合法固话    ":"非法固话");
24     }
25     
26     //切割 通过split
27     //需求:按照空格切割字符串 = 火      影   忍           者
28     public static void cutStr1(String str){
29         String[] splits = str.split(" +");
30         System.out.println("数组元素:" + Arrays.toString(splits));
31     }
32     //需求:按照叠词分割字符串=大家家明天天玩的的的的的开心
33     public static void cutStr2(String str){
34         String[] splits = str.split("(.)\1+");
35         System.out.println("数组元素:" + Arrays.toString(splits));
36     }
37     
38     //替换
39     //字符串去重:大家家明天天玩的的的的的开心
40     public static void replaceSame(String str){    
41         //把后几号替换成****
42         String s = "大家家明13211525558天天玩18356457889的的的的的开心";
43         System.out.println("被替换后的内容" + s.replaceAll("1[3478]\d{9}+", "****"));
44         
45         //去重并替换
46         System.out.println(str.replaceAll("(.)\1+", "$1"));
47         //(.)任意字字符成组,\1捕获1次;叠词,$1得到1组, 取前面的组1次或多次
48     }
49 }

运行结果:

原文地址:https://www.cnblogs.com/K-artorias/p/7355322.html