在以下代码中,(?i:hot)
是一个捕获组。或者至少应该是......它匹配表达式并消耗字符。
但是,当我尝试获取组计数时,它返回 0。
Pattern pattern = Pattern.compile("(?i:hot)");
Matcher matcher = pattern.matcher("hot diggity dog");
while (matcher.find()) {
int groupCount = matcher.groupCount(); // returns 0
for (int i = 0; i <= groupCount; i++) {
System.out.printf("%d. %s%n", i, matcher.group(i));
}
}
括号确实捕获。如您所见,如果我们这样做
matcher.replaceAll("cold")
它将返回“冷数字狗”
我希望 (?i:hot) 等于 ((?i)hot),但事实并非如此。后一种情况是捕获组。
这不是 Java RegEx Matcher.groupCount returns 0 的重复项因为在该问题中,确实没有捕获组,因此 groupCount 正确返回 0。但是就我而言,这确实应该被视为捕获组,因为它确实执行捕获!
最佳答案
就在 documentation 中:
(?idmsux-idmsux:X) X, as a non-capturing group with the given flags i d m s u x on - off
如果您想要一个捕获组,只需将其括在另一组括号中即可:
((?i:hot))
关于java - 为什么捕获组中的标志会删除该组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51941021/