D 的个人博客

但行好事莫问前程

  menu
417 文章
3446695 浏览
10 当前访客
ღゝ◡╹)ノ❤️

Java 正则中的非捕获组

正则表达式中的非捕获组(non-capturing group)用于匹配但不“保存”匹配结果,出现在正则表达式模式中的 (?:pattern) 这部分就是非捕获组。

我试了几个在线的正则表达式测试工具,返回的匹配结果都是“整个组”,不是非捕获组。

imagepng

Java 中 Matcher#group() 返回的是 group(0),也是整个匹配结果,如果要返回第一个非捕获组,需要用 group(1)

1Pattern pattern = Pattern.compile("([0-9]+)(?:st|nd|rd|th)?");
2Matcher matcher = pattern.matcher("1st 2nd 3 4th");
3while (matcher.find()) {
4    System.out.printf("%3s %s\n", matcher.group(), matcher.group(1));
5}

输出:

11st 1
22nd 2
3  3 3
44th 4

另外,使用非捕获组时需要注意结尾的 ?,在上面例子中 ([0-9]+)(?:st|nd|rd|th)? 说明该非捕获组是可选的,如果缺少该 ?,则输出结果:

11st 1
22nd 2
34th 4

因为 3 没有 st|nd|rd|th 结尾,所以没有匹配上。

非捕获组的概念很好理解,在 Java 中获取非捕获组也很简单,但在需要替换匹配的场景下,不能使用非捕获组,因为 Matcher#appendReplacementMatcher#appendTail 或者 Matcher#replace* 并不支持非捕获组替换。