.net RegEx:最小可能匹配或非贪婪匹配

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1919982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 13:41:33  来源:igfitidea点击:

RegEx: Smallest possible match or nongreedy match

.netregexregex-greedynon-greedy

提问by Jonathan Allen

How do I tell RegEx (.NET version) to get the smallest valid match instead of the largest?

如何告诉 RegEx(.NET 版本)获得最小的有效匹配而不是最大的匹配?

回答by DMI

For a regular expression like .*or .+, append a question mark (.*?or .+?) to match as few characters as possible. To optionally match a section (?:blah)?but without matching unless absolutely necessary, use something like (?:blah){0,1}?. For a repeating match (either using {n,}or {n,m}syntax) append a question mark to try to match as few as possible (e.g. {3,}?or {5,7}?).

对于像.*or 之类的正则表达式.+,附加一个问号(.*?.+?)以匹配尽可能少的字符。要可选地匹配某个部分(?:blah)?但除非绝对必要,否则不匹配,请使用类似(?:blah){0,1}?. 对于重复匹配(使用{n,}{n,m}语法),附加一个问号以尝试匹配尽可能少的匹配(例如{3,}?{5,7}?)。

The documentation on regular expression quantifiersmay also be helpful.

有关正则表达式量词的文档也可能有所帮助。

回答by dxh

The non-greedy operator, ?. Like so:

非贪婪运算符,?。像这样:

.*?

回答by Jonathan

The non greedy operator does not mean the shortest possible match:

非贪婪运算符并不意味着可能的最短匹配:

abcabk

abcbk

a.+?kwill match the entire string (in this example) instead of only the last three signs.

a.+?k将匹配整个字符串(在本例中),而不是仅匹配最后三个符号。

I'd like to actually find the smallest possible match instead.

我想实际上找到最小的匹配项。

That is that last possible match for 'a' to still allow all matches for k.

那是 ' a' 的最后一个可能匹配仍然允许k.

I guess the only way to do that is to make use of an expression like:

我想唯一的方法是使用这样的表达式:

a[^a]+?k