1 import java.util.Iterator;
2 import java.util.TreeSet;
3 import java.util.regex.Matcher;
4 import java.util.regex.Pattern;
5
6 public class RegexDemo {
7
8 public static void main(String[] args) {
9 method_8();
10 }
11
12 /*
13 * 需求:定义一个功能对QQ号进行校验。 要求:长度5~15. 只能是数字, 0不能开头
14 */
15 public static void method_1() {
16 String qq = "101885";
17 String regex = "[1-9]\\d{4,14}";
18 System.out.println(qq + ":" + qq.matches(regex));
19 }
20
21 /*
22 * 需求:手机号码验证
23 */
24 public static void method_2() {
25 String tel = "18190029004";
26 String regex = "1[358]\\d{9}";
27 System.out.println(tel + ":" + tel.matches(regex));
28 }
29
30 /*
31 * 需求:叠词切割
32 */
33 public static void method_3() {
34 String str = "akjdhkahjjauuuuqjhadwww;k";
35 String regex = "(.)\\1+";
36 String[] arr = str.split(regex);
37 for (String s : arr) {
38 System.out.println(s);
39 }
40 }
41
42 /*
43 * 需求:替换 1.手机号部分替换 2.叠词替换
44 */
45 public static void method_4() {
46 String tel = "13840056789";
47 String regex = "(\\d{3})(\\d{4})(\\d{4})";
48 System.out.println(tel.replaceAll(regex, "$1****$3"));
49
50 String str = "akjdhkahjjauuuuqjhadwww;k";
51 String reg = "(.)\\1+";
52 System.out.println(str.replaceAll(reg, "*"));
53 }
54
55 /*
56 * 需求:获取 三个字母的单词
57 */
58 public static void method_5() {
59 String str = "ajkdh iqw iqiw qii,wip aido q qw";
60 String regex = "\\b[a-z]{3}\\b";
61 Pattern p = Pattern.compile(regex);
62 Matcher m = p.matcher(str);
63 while (m.find()) {
64 System.out.println(m.group());
65 System.out.println(m.start() + " " + m.end());
66 }
67 }
68 /*
69 * 热热热.热播..播播..播播播.播电电..电影影电电电.电电.视视视..剧
70 * 热播电影电视剧
71 */
72
73 public static void method_6(){
74 String str = "热热热.热播..播播..播播播.播电电..电影影电电电.电电.视视视..剧";
75 String regex = "\\.+";
76 String str1 = str.replaceAll(regex, "");
77 String regex1= "(.)\\1+";
78 System.out.println(str1.replaceAll(regex1, "$1"));
79 }
80
81 /*
82 * 对IP地址排序
83 *
84 */
85
86 public static void method_7(){
87 String str = "192.168.2.3 8.8.8.8 127.0.0.1 10.10.10.1";
88 //加0
89 String regex = "(\\d+)";
90 str = str.replaceAll(regex, "00$1");
91 //去0
92 String reg = "0+(\\d{3})";
93 str = str.replaceAll(reg, "$1");
94 //排序;
95 TreeSet ts = new TreeSet();
96 String[] arr = str.split(" +");
97 for(String s:arr){
98 ts.add(s);
99 }
100 //格式化输出
101 for(Iterator it = ts.iterator();it.hasNext();){
102 String ip = (String) it.next();
103 String re = "0+(\\d{1,3})";
104 ip = ip.replaceAll(re, "$1");
105 System.out.println(ip);
106 }
107 }
108 /*
109 * Email 验证
110 *
111 */
112 public static void method_8(){
113 String str = "a@163.com";
114 String regex = "[a-zA-Z\\d_]+@[a-zA-Z\\d_]+\\.[a-zA-Z]{2,3}";
115 System.out.println(str.matches(regex));
116 }
117 }