开发者

How to make a "minimal match" Regex search in C#? [duplicate]

This question already has answers here: My regex is matching too much. How do I make it stop? [duplicate] (5 answers) Closed 3 years ago.

Let's say I have a multi-line string like this:

STARTFRUIT
banana
ENDFRUIT

STARTFRUIT
avocado
ENDFRUIT

STARTVEGGIE
rhubarb
ENDVEGGIE

STARTFRUIT
lime
ENDFRUIT

I want to search for all fruit, no veggies. I try this:

MatchCollection myMatches = Regex.Matches(tbBlob.Text, "STARTFRUIT.*ENDFRUIT", RegexOptions.Singleline);

foreach (var myMatch in myMatches)
{
    Forms.MessageBox.Show(String.Format("Match: {0}", myMatch), "Match", Forms.MessageBoxButtons.OK, Forms.Mes开发者_开发百科sageBoxIcon.Information);
}

The problem is, instead of returning me an array of three matches, it gives me a big match encompassing the first STARTFRUIT at the beginning and the last ENDFRUIT at the end. Is there a way to "minimalize" the match search? I don't see any help in RegexOptions.


Use a non-greedy modifier (a question mark) after the quantifier:

"STARTFRUIT.*?ENDFRUIT"
             ^
         add this

Note that the question-mark here has a different meaning here than when it is used as a quantifier, where it means "match zero or one".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜