java.util.regex.Pattern类
字符
x 字符 x。举例:'a'表示字符a
\\ 反斜线字符。
\n 新行(换行)符 ('\u000A')
\r 回车符 ('\u000D')
字符类
[abc] a、b 或 c(简单类)
[^abc] 任何字符,除了 a、b 或 c(否定)
[a-zA-Z] a到 z 或 A到 Z,两头的字母包括在内(范围)
[0-9] 0到9的字符都包括
预定义字符类
. 任何字符。我的就是.字符本身,怎么表示呢? \.
\d 数字:[0-9]
\D 非数字:[^\d]/[^0-9]
\w 单词字符:[a-zA-Z_0-9]
\W 非字符[^\w]
边界匹配器
^ 行的开头
$ 行的结尾
\b 单词边界, 就是不是单词字符的地方。
Greedy 数量词
X? X,一次或一次也没有
X* X,零次或多次
X+ X,一次或多次
X{n} X,恰好 n 次
X{n,} X,至少 n 次
X{n,m} X,至少 n 次,但是不超过 m 次
运算符
XY X后跟 Y
X|Y X 或 Y
(X) X,作为捕获组
String类中的三个基本操作使用正则:
匹配:matches()
切割: split()
替换: replaceAll()
下边是一些常用的使用
//以空格分割
String str1 = "1 2 3 4 54 5 6";
String[] numbers = str1.split(" +");
for (String temp : numbers) {
System.out.println(temp);
}
// 替换,替换所有的数字为*
String str2 = "abd123:adad46587:asdadasadsfgi#%^^9090";
System.out.println(str2.replaceAll("[0-9]", "*"));
System.out.println(str2.replaceAll("\\d", "*"));
// 匹配匹配邮箱
String mail1 = "ababc@asa.com";
String mail2 = "ababc@asa.com.cn";
String mail3 = "ababc@asa";
// String mainRegex = "[0-9a-zA-Z_]+@[0-9a-zA-Z_]++(\\.[0-9a-zA-Z_]+{2,4})+";
String mainRegex = "\\w+@\\w+(\\.\\w{2,4})+";
System.out.println(mail1.matches(mainRegex));//true
System.out.println(mail2.matches(mainRegex));//true
System.out.println(mail3.matches(mainRegex));//false