正则表达式
正则的基本语法
[ab] a或者b
[a-z] 所有的小写字母
[a-zA-Z0-9_] 数字字母下划线
[^a] 非字符a
[^ab] 非字符a和非字符b
注意: ^只有在[]内部才表示非, 如果不是在内部表示字符开头
\d 表示数字 等价于 [0-9] (digital)
\D 表示非数字 等级于[^0-9]
\w 表示单词字符串 数字字母下划线 等价于 [a-zA-Z0-9_] (word)
\W 表示非单词字符 等价于 [^a-zA-Z0-9_]
\s 表示空白字符 space 空格 \n \r \t
\S 非空白字符
. 表示任意字符 去除: \n \r
\. 只匹配真正的 .
^ 表示字符串的开头
$ 字符串的结尾
数量词
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 取第一组
java中的正则
Pattern 模式
Matcher 匹配器
支持正则的4种方法
match
String s = "a";
boolean matches = s.matches("\\w");
System.out.println(matches);
split
String s = "aaaa555bbbb6cccc88dddd";
String[] splits = s.split("\\d+");
for (String split : splits) {
System.out.println(split);
}
replaceFirst
String s = "aaa123aaa";
String result = s.replaceFirst("a+", "yyy");
System.out.println(result);
replaceAll
String s = "aaa123aaa";
String result = s.replaceAll("a+", "yyy");
System.out.println(result);
两种模式
贪婪式
String s = "aaaa34a9231aa033aa";
System.out.println(s.replaceAll("\\d+", "@"));
懒惰式
String s = "aaaa34a9231aa033aa";
System.out.println(s.replaceAll("\\d+?", "@"));
例题
手机号是否合法
String s = "15958767788";
boolean matches = s.matches("1[345678]\\d{9}");
System.out.println(matches);
手机号脱敏
String s = "15958767788";
String result = s.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
System.out.println(result);
邮箱是否合法
String s = "woshiyega@126.com";
boolean matches = s.matches("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+");
System.out.println(matches);
治疗口吃
String s = "今今天天我我我我要要请你们洗洗脚";
String result = s.replaceAll("(.)\\1+", "$1");
System.out.println(result);
切分IP地址
String s = ".192.168.2..100.......";
String[] splits = s.split("\\.");
System.out.println(Arrays.toString(splits));