java中正则(Regular Expression)使用
String类中matches方法
public boolean matches(String regex) {
return Pattern.matches(regex, this);
}
Pattern中matches方法
public static boolean matches(String regex, CharSequence input) {
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
return m.matches();
}
常用元字符
\ ^ $ * + ? {n} {n,} {n,m} (pattern) (?:pattern) (?=pattern) (?!pattern) (?<=pattern) (?<!pattern) x|y [xyz] [^xyz] [a-z] [^a-z] \b \B \d \D \n \s \S \t \w \W
字符组简写\d等价[0-9] \w代表单词字符,等价[0-9a-zA-Z] \s表示空白字符等价[\t\r\n\v\f]
\d和\D互补,即\D表示匹配不是数字的 同理\S \W
[\s\S]匹配所有字符
元字符: - [ $ ^ 作为普通字符时需要转义,使用反斜线字符 \
"-"用来表示范围
"."用来匹配任意字符,除了换行符\n
排除型字符组:[^0-9]不是数字
java中提供了字符组运算的功能,例如匹配左右小写辅音字母[[a-z]&&[^aoeiu]]
限定符
* 等价{0, }
+ 等价{1, }
? 等价{0, 1}最多出现一次,也可以没有出现
{n} n是一个非负整数,匹配确定的n次
{n,} 至少匹配n次
{n,m{ 最少n次且最多匹配m次
定位符
^ 匹配字符串开始位置
$ 匹配字符串结尾位置
\b 匹配一个单词边界, 即字与空格间的位置
\B 匹配非单词边界
选择
(...|...)
断言
常见断言单词边界、行起始/结束位置、环视
正则表达式提供专用的单词边界\b ,例如匹配单词row "\brow\b"
行起始^ 终止$
环视 (环视结构不匹配任何字符,只匹配文本中的特定位置。这一特点与锚点^和$很相似。但是环视功能更强大)
(?=...) 肯定顺序环视 子表达式能都匹配右侧文本
// 顺序环视
Pattern pattern = Pattern.compile("\\w*(?=\\.exe)");
Matcher matcher = pattern.matcher("aaa.exe,bbb.exe,ccc.txt,ddd.sh");
while (matcher.find()) {
System.out.println(matcher.group());
}
输出:
aaa
bbb
(?!...) 否定顺序环视
// 否定顺序环视
Pattern pattern = Pattern.compile("\\w+(?!\\.exe)\\.\\w+");
Matcher matcher = pattern.matcher("aaa.exe,bbb.exe,ccc.txt,ddd.sh");
while (matcher.find()) {
System.out.println(matcher.group());
}
输出:
ccc.txt
ddd.sh
(?<=...) 肯定逆序环视
// 肯定逆序环视
Pattern pattern = Pattern.compile("(?<=bbb)\\.\\w+");
Matcher matcher = pattern.matcher("aaa.exe,bbb.exe,ccc.txt,ddd.sh,bbb.sh");
while (matcher.find()) {
System.out.println(matcher.group());
}
输出:
.exe
.sh
(?<!...) 否定逆序环视
// 否定逆序环视
Pattern pattern = Pattern.compile("(?<!bbb)\\.\\w+");
Matcher matcher = pattern.matcher("aaa.exe,bbb.exe,ccc.txt,ddd.sh,bbb.sh");
while (matcher.find()) {
System.out.println(matcher.group());
}
输出:
.exe
.txt
.sh
匹配邮箱
Pattern pattern = Pattern.compile("[\\w_.%+-]+@[\\w.-]+\\.[a-zA-Z]{2,6}");
Matcher matcher = pattern.matcher("123,test@runoob.com,eee,zhu@com.cn aaa@11.cc");
// matches()方法只有在完全匹配时返回true,匹配不上和部分匹配都返回false
// System.out.println(matcher.matches()) // --> false
// find()方法在部分匹配时和完全匹配时返回true,匹配不上返回false
while (matcher.find()) {
System.out.println(matcher.group());
}
控制台结果输出:
test@runoob.com
zhu@com.cn
aaa@11.cc