Greedy, Non-Greedy, All-Greedy Matching in C# Regex

Peter Lee picture Peter Lee · Oct 10, 2010 · Viewed 39.2k times · Source

How can I get all the matches in the following example:

// Only "abcd" is matched
MatchCollection greedyMatches = Regex.Matches("abcd", @"ab.*");

// Only "ab" is matched
MatchCollection lazyMatches   = Regex.Matches("abcd", @"ab.*?");

// How can I get all matches: "ab", "abc", "abcd"

P.S.: I want to have the all matches in a generic manner. The example above is just an example.

Answer

Tseng picture Tseng · Oct 10, 2010

You could use something like:

MatchCollection nonGreedyMatches = Regex.Matches("abcd", @"(((ab)c)d)");

Then you should have three backreferences with ab, abc and abcd.

But, to be honest, this kind of regex doesn't makes too much sense, especially when it gets bigger it becomes unreadable.

Edit:

MatchCollection nonGreedyMatches = Regex.Matches("abcd", @"ab.?");

And you got an error there btw. This can only match ab and abc (read: ab + any (optional) character

Lazy version of:

MatchCollection greedyMatches    = Regex.Matches("abcd", @"ab.*");

is:

MatchCollection nonGreedyMatches    = Regex.Matches("abcd", @"ab.*?");