正则表达式量词和字符类
在Java Tutorial中有正则表达式量词的例子和描述。
贪婪 - 吃完整的字符串,然后退出一个字符,然后再试一次
Regex: .*foo // greedy
String to search: xfooxxxxxxfoo
Found "xfooxxxxxxfoo"
不情愿 - 从一开始就开始,然后一次吃一个角色
Regex: .*?foo // reluctant quantifier
String to search: xfooxxxxxxfoo
Found "xfoo", "xxxxxxfoo"
拥有 - 吃整个字符串尝试一次匹配
Regex: .*+foo // possessive quantifier
String to search: xfooxxxxxxfoo
No match found
他们没事,我理解他们,但有人可以向我解释当正则表达式更改为角色类时会发生什么? 还有其他规则吗?
Regex: [fx]*
String to search: xfooxxxxxxfoo
Found "xf","","","xxxxxxf","","","",""
Regex: [fx]*?
String to search: xfooxxxxxxfoo
Found 15 zero-length matches
Regex: [fx]*+
String to search: xfooxxxxxxfoo
Found "xf","","","xxxxxxf","","","",""
它将量词(贪婪,不情愿/懒惰,占有欲)应用于整个角色类。 这意味着它将匹配(贪婪,懒惰等)字符类中的每个文字字符。
Regex: [fx]*
String to search: xfooxxxxxxfoo
Found "xf","","","xxxxxxf","","","",""
所以它寻找零或更多的f
或x
。 引擎找到匹配的xf
。 它也匹配两个o
周围的空串。 然后匹配连续的x
,因为它是f
或x
的零个或多个 。
我会查看regex101.com了解正则表达式的更多细节,特别是左侧边栏上的调试器部分
链接地址: http://www.djcxy.com/p/13423.html上一篇: Regex quantifiers and character classes
下一篇: Using capturing groups with reluctant, greedy, and possessive quantifiers