`Greedy`和`Reluctant`正则表达式量词有什么区别? [英] What is the difference between `Greedy` and `Reluctant` regular expression quantifiers?
本文介绍了`Greedy`和`Reluctant`正则表达式量词有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
来自 模式
javadocs:
From the Pattern
javadocs:
Greedy quantifiers:
X? X, once or not at all
X* X, zero or more times
X+ X, one or more times
X{n} X, exactly n times
X{n,} X, at least n times
X{n,m} X, at least n but not more than m times
Reluctant quantifiers:
X?? X, once or not at all
X*? X, zero or more times
X+? X, one or more times
X{n}? X, exactly n times
X{n,}? X, at least n times
X{n,m}? X, at least n but not more than m times
他们所做的描述是相同的...那么,什么是差异?
The description of what they do is the same...so, what is the difference?
我真的很感激一些例子。
I would really appreciate some examples.
我用Java编码,但我听到这个概念对于大多数现代正则表达式实现都是一样的。
推荐答案
贪婪的运营商总是试图抓住尽可能多的输入,而不情愿的量词将尽可能少地匹配输入并仍然创建匹配。
A greedy operator always try to "grab" as much of the input as possible, while a reluctant quantifier will match as little of the input as possible and still create a match.
示例:
"The red fox jumped over the red fence"
/(.*)red/ => \1 = "The red fox jumped over the "
/(.*?)red/ => \1 = "The "
"aaa"
/a?a*/ => \1 = "a", \2 = "aa"
/a??a*/ => \1 = "", \2 = "aaa"
"Mr. Doe, John"
/^(?:Mrs?.)?.*\b(.*)$/ => \1 = "John"
/^(?:Mrs?.)?.*?\b(.*)$/ => \1 = "Doe, John"
这篇关于`Greedy`和`Reluctant`正则表达式量词有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文