gpt4 book ai didi

Java 正则表达式 - 添加括号使其变得贪婪?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:22:14 25 4
gpt4 key购买 nike

public void name() throws Exception {
Pattern p = Pattern.compile("\\d{1,2}?");
String input = "09";
Matcher m = p.matcher(input);
StringBuffer sb = new StringBuffer();
while(m.find()) {
System.out.println("match = "+m.group());
}
}

上述方法的输出是:

match = 0
match = 9

现在,我只是在正则表达式中添加括号:

public void name() throws Exception {
Pattern p = Pattern.compile("(\\d{1,2})?");
String input = "09";
Matcher m = p.matcher(input);
StringBuffer sb = new StringBuffer();
while(m.find()) {
System.out.println("match = "+m.group());
}
}

输出变成:

match = 09
match =
  1. 为什么括号在这里使匹配贪婪
  2. [编辑,稍后添加]为什么第一种情况不匹配空字符串?

最佳答案

为了量词 (?, *, + or {n,m})不情愿(非贪婪或懒惰),它必须后跟 ?。因此,模式 \\d{1,2}? 是不情愿的。

另一方面,(\\d{1,2})?两层贪婪量词组成:

  1. 一组 (\\d{1,2}) 包含带有贪婪量词 {1,2} 的模式,
  2. 后跟 ? 贪婪量词。

因此,(\\d{1,2})? 是贪心的,因为 ? 不会立即跟随量词(有是闭合组之间的括号),因此它充当不情愿的正则表达式的元字符。

参见 this page about quantifiers作为引用。

关于Java 正则表达式 - 添加括号使其变得贪婪?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41512597/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com