語法
字符 | 含義 |
---|---|
\ | 將下一字符標(biāo)記為特殊字符 |
^ | 匹配開始 |
$ | 匹配結(jié)束 |
* | 0次或多次匹配前面的字符 |
+ | 1次或多次匹配前面的字符 |
? | 0次或1次匹配前面的字符,跟在其它限定符后匹配盡可能段的字符串(非貪心) |
{n} | 匹配n次 |
{n,} | 至少匹配n次 |
{n,m} | 匹配n~m次 |
(pattern) | 匹配組 |
x|y | 匹配x或y |
[xyz] | 字符集,匹配任一字符 |
[^xyz] | 反向字符集,匹配不包含的字符 |
[a-z] | 匹配小寫字母 |
\d | 匹配數(shù)字 |
\n | 匹配換行符 |
\r | 匹配回車符 |
\s | 匹配任何空白字符 |
\w | 匹配任何字類字符 |
java.util.regex
Pattern
判斷是否匹配
boolean isMatch = Pattern.matches(regex, text);
Matcher
捕獲組
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
if (matcher.find()) {
System.out.println(matcher.group());
} else {
System.out.println("NOT FOUND");
}
示例:
// 通過()來建立分組
String regex = "https://github\\.com/(\\w+)/(.*)";
String text = "https://github.com/wch853/jianshu";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
if (matcher.find()) {
for (int i = 0; i <= matcher.groupCount(); i++) {
/**
* 通過group(int group);來捕獲組
* group(); / group(0); 捕獲所有
* group(i)捕獲第i個(gè)分組
*/
System.out.println("group:" + i + ": " + matcher.group(i));
}
} else {
System.out.println("NOT FOUND");
}