简体   繁体   English

正则表达式量词和字符类

[英]Regex quantifiers and character classes

There are examples and descriptions of regex quantifiers in Java Tutorial. Java教程中提供了正则表达式量词的示例和说明。

Greedy - eats full string then back off by one character and try again 贪婪-先吃完整串然后再退一个字符然后重试

 Regex: .*foo // greedy String to search: xfooxxxxxxfoo Found "xfooxxxxxxfoo" 

Reluctant - start at the beginning then eat one character at a time 不情愿-从头开始,然后一次吃一个角色

 Regex: .*?foo // reluctant quantifier String to search: xfooxxxxxxfoo Found "xfoo", "xxxxxxfoo" 

Possessive - eats the whole string trying once for match 拥有-尝试一次尝试吃整个字符串

 Regex: .*+foo // possessive quantifier String to search: xfooxxxxxxfoo No match found 

They are ok and I understand them, but can someone explain to me what happens when regex is changed to the character class? 它们还可以,我理解它们,但是有人可以向我解释一下,将正则表达式更改为字符类时会发生什么? Are there any other rules? 还有其他规定吗?

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

It applies the quantifier (greedy, reluctant/lazy, possessive) to the entire character class. 它将量词(贪婪,不情愿/懒惰,占有欲)应用于整个角色类。 This means it will match (greedily, lazily, etc) each literal character in the character class. 这意味着它将匹配(贪婪地,懒惰地等)字符类中的每个文字字符。

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

So it looks for zero or more of f or x . 因此它寻找fx零个或多个。 The engine finds xf which matches. 引擎找到匹配的xf It also matches on the empty string around the two o 's. 它还匹配两个o周围的空字符串。 It then matches the consecutive x 's because it's zero or more of f or x . 然后,它匹配连续的x ,因为它是fx的零或更大

I would check out regex101.com for more detail on regexes, especially the debugger portion on the left sidebar 我会在regex101.com上查看有关regexes的更多详细信息,尤其是左侧栏中的调试器部分

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM