正则表达式用于操作字符串数据
是通过一些特定的符号来实现这些操作
字符类 | |
---|---|
[abc] | a、b 或 c(简单类) |
[^abc] | 任何字符,除了 a、b 或 c(否定) |
[a-zA-Z] | a 到 z 或 A 到 Z,两头的字母包括在内(范围) |
[a-d[m-p]] | a 到 d 或 m 到 p:[a-dm-p](并集) |
[a-z&&[def]] | d、e 或 f(交集) |
[a-z&&[^bc]] | a 到 z,除了 b 和 c:[ad-z](减去) |
[a-z&&[^m-p]] | a 到 z,而非 m 到 p:[a-lq-z](减去) |
预定义字符类 | |
. | 任何字符(与行结束符可能匹配也可能不匹配) |
\d | 数字:[0-9] |
\D | 非数字: [^0-9] |
\s | 空白字符:[ \t\n\x0B\f\r] |
\S | 非空白字符:[^\s] |
\w | 单词字符:[a-zA-Z_0-9] |
\W | 非单词字符:[^\w] |
边界匹配器 | |
---|---|
^ | 行的开头 |
$ | 行的结尾 |
\b | 单词边界 |
\B | 非单词边界 |
\A | 输入的开头 |
\G | 上一个匹配的结尾 |
\Z | 输入的结尾,仅用于最后的结束符(如果有的话) |
\z | 输入的结尾 |
Greedy 数量词 | |
X? | X,一次或一次也没有 |
X* | X,零次或多次 |
X+ | X,一次或多次 |
X{n} | X,恰好 n 次 |
X{n,} | X,至少 n 次 |
X{n,m} | X,至少 n 次,但是不超过 m 次 |
1,匹配 使用的是String的matches方法
String tel = "12854803220";
String regex = "1[358][0-9]{9}";
boolean b = tel.matches(regex);
System.out.println(tel+":"+b);
2,切割 使用的是String的split方法
String str = "tom###jerry&@@spike";
String regex = "[&#@]+";
String[] names = str.split(regex);
for(String name:names)
{
System.out.println(name);
}
结果:
tom
jerry
spike
3,替换 使用的是String的replaceAll方法
String str = "tom###jerry@@@@spike";
String regex = "";
//.表示代表任意的字符 (.)代表任意字符且是分组 代表第一组 \\1是使用第一组的字符
//+ 是代表一个或多个 后面的$1是使用前面的第一个分组
String res = str.replaceAll("(.)\\1+","$1");
System.out.println(res);
结果:
tom#jery@spike
String tel = "15578980301";
String str = tel.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
System.out.println(str);
结果:
155****0301
4,获取
将正则表达式封装成对象
Pattern p = Pattern.compile("a*b");
通过正则对象的matcher方法与字符串关联,获取对字符串操作的匹配其对象Matcher
Matcher m = p.matter("aaaaab");
通过Matcher对象匹配器的方法对字符串进行操作
boolean b = m.matches();
//获取字符串中的三个字母的单词
String mess = "we are the champions";
String regex = "\\b[a-z]{3}\\b";
//将正则表达式封装成对象
Pattern p = Pattern.compile(regex);
//通过正则表达式对象获取匹配其对象
Matcher m = p.matcher(mess);
//使用Matcher对象的方法对字符串操作
while(m.find())
{
System.out.println(m.group());//获取匹配的子序列
}
结果:
are
the
实例
public static void test_1() {
//将此字符串恢复成万物皆对象
String str = "万万...万万...万物.物.物.物皆...皆.皆..皆皆对..对.对.象..";
System.out.println(str);
//现将 . 去掉
str = str.replaceAll("\\.", "");
System.out.println(str);
//将重复的字去掉
str = str.replaceAll("(.)\\1+","$1");
System.out.println(str);
}
结果:
万万...万万...万物.物.物.物皆...皆.皆..皆皆对..对.对.象..
万万万万万物物物物皆皆皆皆皆对对对象
万物皆对象
public static void test_2() {
//邮件地址合法性判断
String mail = "TomandJerry123@999.com";
String regex = "[a-zA-Z0-9_]+@[a-zA-Z0-9]+\\.[a-zA-Z]+";
boolean b = mail.matches(regex);
System.out.println(mail+":"+b);
}
结果:
TomandJerry123@999.com:true