您如何解释空正则表达式和空捕获组正则表达式返回字符串长度加一个结果?
代码
public static void main(String... args) {
{
System.out.format("Pattern - empty string\n");
String input = "abc";
Pattern pattern = Pattern.compile("");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
String s = matcher.group();
System.out.format("[%s]: %d / %d\n", s, matcher.start(),
matcher.end());
}
}
{
System.out.format("Pattern - empty capturing group\n");
String input = "abc";
Pattern pattern = Pattern.compile("()");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
String s = matcher.group();
System.out.format("[%s]: %d / %d\n", s, matcher.start(),
matcher.end());
}
}
}
输出
Pattern - empty string
[]: 0 / 0
[]: 1 / 1
[]: 2 / 2
[]: 3 / 3
Pattern - empty capturing group
[]: 0 / 0
[]: 1 / 1
[]: 2 / 2
[]: 3 / 3
最佳答案
正则表达式引擎被硬编码为在零长度匹配(否则无限循环)时前进一个位置。您的正则表达式匹配零长度子字符串。每个字符之间都有零长度子串(想想“每个字符之间的间隙”);此外,正则表达式引擎还会考虑字符串有效匹配位置的开始和结束。因为长度为 N
的字符串在字母之间包含 N+1
间隔(计算开始和结束,正则表达式引擎会这样做),您将得到 N+ 1
匹配。
关于java - 为什么空正则表达式和空捕获组正则表达式返回字符串长度加一结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16103346/