1

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","","","",""
4

1 回答 1

4

它将量词(贪婪、不情愿/懒惰、占有欲)应用于整个字符类。这意味着它将匹配(贪婪,懒惰等)字符类中的每个文字字符。

Regex: [fx]*
String to search: xfooxxxxxxfoo
Found "xf","","","xxxxxxf","","","",""

所以它寻找零个或多个for x。引擎找到xf匹配的。它还匹配两个o's 周围的空字符串。然后它匹配连续x的 's,因为它是 or 的零个或多个fx

我会查看regex101.com以获取有关正则表达式的更多详细信息,尤其是左侧边栏上的调试器部分

于 2014-08-07T19:49:18.800 回答