上的调试器部分。
Java教程中有正则表达式量词的示例和描述。
贪心-吃掉整个字符串,然后后退一个字符,再试一次
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
,因为它是0 或f
或x
的多个。
我会查看regex101.com以获得更多关于正则表达式的详细信息,特别是左侧栏