java - 试图用 Java 理解正则表达式中的 "Capturing groups"

标签 java regex capture

我正在学习 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

您将匹配整个字符串。现在假设您只需要 14203。没问题 - 正则表达式库允许您将两个 \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));
}

这会打印 14203

Demo on ideone .

关于java - 试图用 Java 理解正则表达式中的 "Capturing groups",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16038206/

相关文章:

java - Java 指针写入是原子的吗?

c++ - 样本量 8 还是 16?

C# 屏幕捕获虚拟桌面

java - ConcurrentHashMap 上的同步是否正确?

java - 不刷新的随机数生成器

javascript - Python 和 Javascript 正则表达式有什么不同?

javascript - 用于 Markdown 强调的正则表达式,带有星号 * 和下划线 _

mysql - 使用 SQL 查询在单词列表中查找精确的单词匹配

java - 无法在 ImageView 中显示相机 Activity 的结果

java - 该行是否存在?如果是更新它,如果不是添加它 mysql/java