Java正则的贪婪和非贪婪模式
定义
- 贪婪模式:匹配尽可能多的字符
- 非贪婪模式:匹配尽可能少的字符
在Java
的正则表达式中,通过在修饰匹配次数的符号后面加一个?
,即非贪婪模式,默认情况下是贪婪模式。
表示匹配次数的符号有:
.? # 任意字符匹配1次或0次 .* # 任意字符匹配0次或多次 .+ # 任意字符匹配1次或多次 .{n} # 任意字符匹配n次 .{n,} # 任意字符匹配至少n次 .{n,m} # 任意字符匹配至少n次,至多m次
代码
public static void main(String[] args) { String input = "aaaabc"; String regex1 = "a{2,3}"; // 贪婪模式 Pattern p1 = Pattern.compile(regex1); Matcher m1 = p1.matcher(input); while (m1.find()) { System.out.println(m1.group()); } System.out.println("------------------"); String regex2 = "a{2,3}?"; // 非贪婪模式 Pattern p2 = Pattern.compile(regex2); Matcher m2 = p2.matcher(input); while (m2.find()) { System.out.println(m2.group()); } }
输出:
aaa ------------------ aa aa
原文链接
https://segmentfault.com/a/11...
相关推荐
qidu 2020-07-05
山水沐光 2020-05-25
lrjnlp 2020-07-19
flyingssky 2020-07-05
杨德龙 2020-11-11
满地星辰 2020-09-16
梦的天空 2020-08-25
flyingssky 2020-06-27
RuoShangM 2020-06-17
天高任鸟飞 2020-06-13
Darklovy 2020-06-11
qidu 2020-06-08
Darklovy 2020-06-07
jyj00 2020-06-06
flyingssky 2020-06-04