Regex :
- 本文介绍正则表达式中匹配的三种量词:贪婪(Greedy)、勉强(Reluctant)、独占(Possessive)
- 本文的正则表达式在 Java 中测试 ,下面讲解三种量词匹配的区别的时候用的是同一个字符串:
- Ggicci's Blog
- Ggicci's Facebook
在笔记 1 中讲到过 ?(重复0次或1次)、*(重复0次或多次)、+(重复1次或多次)。
Greedy Quantifiers
贪婪Reluctant Quantifiers
勉强Possessive Quantifiers
独占X? X?? X?+ X* X*? X*+ X+ X+? X++ X{n} X{n}? X{n}+ X{n,} X{n,}? X{n,}+ X{n,m} X{n,m}? X{n,m}+
Greedy :
匹配最长。在贪婪量词模式下,正则表达式会尽可能长地去匹配符合规则的字符串,且会回溯。
代码:
1: String source = "";
- Ggicci's Blog
- Ggicci's Facebook
2: Pattern pattern = Pattern.compile(".* ");
3: Matcher matcher = pattern.matcher(source);
4: while (matcher.find()) {
5: System.out.println(matcher.group());
6: }
1:
//输出:
2: <li>Ggicci's Blogli><li>Ggicci's Facebookli>
解释:首先 .* 匹配任何字符(在非 DOTALL 模式下不匹配 \n,\r,\a 一类字符),在 source 中第一个被匹配的
Reluctant :
匹配最短。在勉强量词模式下,正则表达式会匹配尽可能短的字符串。
代码:
1: String source = "";
- Ggicci's Blog
- Ggicci's Facebook
2: Pattern pattern = Pattern.compile(".*? ");
3: Matcher matcher = pattern.matcher(source);
4: while (matcher.find()) {
5: System.out.println(matcher.group());
6: }
1:
//输出:
2: <li>Ggicci's Blogli>
3: <li>Ggicci's Facebookli>
解释:source 中第一个
Possessive :
同贪婪一样匹配最长。不过在独占量词模式下,正则表达式尽可能长地去匹配字符串,一旦匹配不成功就会结束匹配而不会回溯。
代码:
1: String source = "";
- Ggicci's Blog
- Ggicci's Facebook
2: Pattern pattern = Pattern.compile(".*+ ");
3: Matcher matcher = pattern.matcher(source);
4: while (matcher.find()) {
5: System.out.println(matcher.group());
6: }
解释:这段正则表达式将不会在 source 找到任何匹配的内容,因为
End :
Author : Ggicci
Java 学习笔记整理,谢谢阅读,有误请指正!