我正在学习 java OCP,目前我还停留在理解 "Capturing groups" 上。部分。这是一种过于抽象的描述方式。能否请您(如果您有时间)给我一些使用“捕获组”的真实示例?
有人能给我提供以下陈述的具体例子吗?
Capturing groups are a way to treat multiple characters as a single unit. They are created by placing the characters to be grouped inside a set of parentheses. For example, the regular expression (dog) creates a single group containing the letters "d" "o" and "g". The portion of the input string that matches the capturing group will be saved in memory for later recall via backreferences (as discussed below in the section, Backreferences).
我很确定我会在看到具体示例后立即了解它。
提前致谢。
最佳答案
除其他外,正则表达式可让您获取与正则表达式的各个部分匹配的输入部分。有时您需要整场比赛,但通常只需要比赛的一部分。例如,此正则表达式匹配 "Page X of Y"
字符串:
Page \d+ of \d+
如果你给它传递一个字符串
Page 14 of 203
您将匹配整个字符串。现在假设您只需要 14
和 203
。没问题 - 正则表达式库允许您将两个 \d+
括在括号中,然后仅检索 "14"
和 "203"
字符串比赛。
Page (\d+) of (\d+)
上面的表达式创建了两个捕获组。通过匹配模式获得的 Matcher
对象允许您单独检索这些组的内容:
Pattern p = Pattern.compile("Page (\\d+) of (\\d+)");
String text = "Page 14 of 203";
Matcher m = p.matcher(text);
if (m.find()) {
System.out.println(m.group(1));
System.out.println(m.group(2));
}
这会打印 14
和 203
。
关于java - 试图用 Java 理解正则表达式中的 "Capturing groups",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16038206/