掌握这些正则表达式就够了!!!

正则的基本语法 含义
[ab] a或者b
[a-z] 所有的小写字母
[a-zA-Z0-9] 数字字母下划线
[^a] 非字符a 注意:^只有在[]内部才表示非,如果不是在内部表示字符开头
\d 表示数字 等价[0-9] (digital)
\D 表示非数字 等价于[^0-9]
\w 表示单词字符串 数字字母下划线 等价于[a-zA-Z0-9_] (word)
\W 表示非单词字符 等价于[^a-zA-Z0-9_]
\s 表示空白字符 space 空格 \n \r \t
\S 非空白字符
. (点) 表示任意字符
数量词 含义
a{m} 整好m个a
a{m,} 至少m个a
a{m,n} 至少m个a,至多n个 大于等于m小于等于n
a+ 表示至少一个 等价于a{1,}
a* 表示至少0个 a{0,}
a? 要么0个要么1个 a{0,1}
捕获组 含义
\1 取第一组

接下来我们就实战演练一下吧
1.验证电话号码
需求:第二位数必须是3-8,11位数字

String s = "16030716341";
boolean result = s.matches("1[345678]\\d{9}");
System.out.println(result);

结果true
2.验证邮箱

String s = "[email protected]";
boolean result = s.matches("\\w{3,15}@\\S+\\.com|cn|edu|org");
System.out.println(result);

结果true
3.将数字取代成@ 如果连续是数字,照样是一个@

String s = "sadasd116dasda11d5dadad"; System.out.println(s.replaceAll("\\d+","@"));

结果sadasd@dasda@d@dadad
4.将连续重复的字,只取第一个(这个运用了捕获组

String s = "我我爱爱爱你你的的闺蜜蜜蜜蜜蜜";
System.out.println(s.replaceAll("(.)\\1+","$1"));

5.将电话号码4-7位打上*号(在业务中经常用)

String s = "13619008304";
        System.out.println(s.replaceAll("(\\d{3})(\\d{4})(\\d{4})","$1****$3"));

结果136****8304
6.切割ip

String s = "192.168.2.100.";
String[] split = s.split("\\.");
System.out.println(Arrays.toString(split));

结果[192, 168, 2, 100]

猜你喜欢

转载自blog.csdn.net/qq_46548855/article/details/108006193