捕获组是一种将多个字符视为一个单元的方法。通过将要分组的字符放在一组括号内来创建它们。例如,正则表达式(dog)创建包含字母单个组d, o和g。
正则表达式还可以定义与模式部分相对应的其他捕获组。除了整个表达式定义的组外,正则表达式中的每对括号还定义了一个单独的捕获组。
package org.nhooo.example.regex; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CapturingGroupDemo { public static void main(String[] args) { // 定义正则表达式以查找单词“ the”或“ quick” String regex = "(the)|(quick)"; String text = "the quick brown fox jumps over the lazy dog"; // 将给定的正则表达式编译为模式,然后 // 创建一个匹配器,将匹配给定的输入 // 这种模式。 Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(text); // 查找每个匹配并打印 while (matcher.find()) { System.out.format("Text \"%s\" found at %d to %d.%n", matcher.group(), matcher.start(), matcher.end()); } } }
该程序的结果是:
Text "the" found at 0 to 3. Text "quick" found at 4 to 9. Text "the" found at 31 to 34.