正则表达式量词和字符类

时间:2014-08-07 19:44:57

标签: java regex quantifiers

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

1 个答案:

答案 0 :(得分:4)

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

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

因此,它会查找fx中的零个或多个。引擎找到匹配的xf。它还匹配两个o周围的空字符串。然后它会匹配连续的x,因为它是fx或更多

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