【发布时间】:2017-01-06 19:06:35
【问题描述】:
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 =
- 为什么括号会使匹配的贪婪在这里?
- [编辑,稍后添加]为什么第一种情况下空字符串不匹配?
【问题讨论】:
标签: java regex regex-greedy