目录
一、正则匹配1.1、精确匹配1.2、模糊匹配1.2.1 单次匹配1.2.2 重复匹配1.2.3 复杂匹配
二、常见操作2.1、匹配(matches)2.2、分割(split)2.3、替换(replaceAll)2.4、搜索并获取
一、正则匹配
正则表达式只用于操作字符串数据,java标准库的正则表达式解析引擎位于java.util.regex包中。
1.1、精确匹配
正则表达式abc,它只能精确匹配字符串"abc",无法匹配到"abcd"、“ABC”、"aBc"等其它字符串。 若正则表达式中含有特殊字符,必须要用\来转义;由于\也是Java的转义字符之一,所以正则表达式\\,它匹配单个反斜杠。 精确匹配实际上等同于String.equals(),实际上用处并不大。
1.2、模糊匹配
1.2.1 单次匹配
序号正则表达式匹配说明
1.
任
何
一
个
\color{red}{任何一个}
任何一个字符2\d
任
何
一
个
\color{red}{任何一个}
任何一个数字3\w
任
何
一
个
\color{red}{任何一个}
任何一个单词字符(字母、数字、下划线)4\s
任
何
一
个
\color{red}{任何一个}
任何一个空白字符(空格符、水平制表符、垂直制表符、换行符、回车符、换页符)5\D
任
何
一
个
\color{red}{任何一个}
任何一个非数字6\W
任
何
一
个
\color{red}{任何一个}
任何一个非单词字符7\S
任
何
一
个
\color{red}{任何一个}
任何一个非空白字符
1.2.2 重复匹配
序号正则表达式匹配说明
1X*X,
零
次
或
多
次
\color{blue}{零次或多次}
零次或多次2X+X,
一
次
或
多
次
\color{blue}{一次或多次}
一次或多次3X?X,
一
次
或
一
次
也
没
有
\color{blue}{一次或一次也没有}
一次或一次也没有4X{n}X,
恰
好
n
次
\color{blue}{恰好n次}
恰好n次5X{n,}X,
至
少
n
次
\color{blue}{至少n次}
至少n次6X{n,m}X,
至
少
n
次
,
但
是
不
超
过
m
次
\color{blue}{至少n次,但是不超过m次}
至少n次,但是不超过m次
1.2.3 复杂匹配
序号正则表达式匹配说明
1^
行
的
开
头
\color{green}{行的开头}
行的开头2$
行
的
结
尾
\color{green}{行的结尾}
行的结尾3[abc]
a
、
b
或
c
\color{green}{a、b或c}
a、b或c4[^abc]任何字符,
除
了
a
、
b
或
c
\color{green}{除了a、b或c}
除了a、b或c5[a-zA-Z]
a
到
z
或
A
到
Z
\color{green}{a到z或A到Z}
a到z或A到Z6ab|c|d
a
b
、
c
或
d
\color{green}{ab、c或d}
ab、c或d7(a)c(e)
分
组
匹
配
\color{green}{分组匹配}
分组匹配
二、常见操作
2.1、匹配(matches)
String input
= "15812345678";
String regex
= "1[358]\\d{9}";
boolean b
= input
.matches(regex
);
System
.out
.println(b
);
Pattern p
= Pattern
.compile(regex
);
Matcher m
= p
.matcher(input
);
boolean b
= m
.matches();
2.2、分割(split)
String input
= "BobttttAlicemmmmmTom";
String regex
= "(.)\\1+";
String
[] arr
= input
.split(regex
);
System
.out
.println(Arrays
.toString(arr
));
Pattern p
= Pattern
.compile(regex
);
String
[] arr
= p
.split(input
);
System
.out
.println(Arrays
.toString(arr
));
2.3、替换(replaceAll)
String input
= "15812345678";
String regex
= "(\\d{3})(\\d{4})(\\d{4})";
String s
= input
.replaceAll(regex
, "$1****$3");
System
.out
.println(s
);
Pattern p
= Pattern
.compile(regex
);
Matcher m
= p
.matcher(input
);
if (m
.matches())
{
String s
= m
.replaceAll("$1****$3");
System
.out
.println(s
);
}
2.4、搜索并获取
String input
= "Moderation is for cowards.";
String regex
= "\\b\\w*o\\w*\\b";
Pattern p
= Pattern
.compile(regex
);
Matcher m
= p
.matcher(input
);
while (m
.find())
{
String s
= input
.substring(m
.start(), m
.end());
System
.out
.println(s
);
}