C# - Regex - How to make an expression non-greedy

Append a question mark 

?

to make your regular expression non-greedy.

In the example below, we create an expression to match all HTML span elements. The greedy version of the example produces a very different — and unexpected — result.


*

Using the
Greedy quantifier

Greedy

*?

Using the
Non-greedy quantifier

Non-greedy

Input:
one <span>two</span> three <span>four</span> five
one <span>two</span> three <span>four</span> five
Pattern:

"<span>.*</span>"

"<span>.*?</span>"

Match Count:
1
2
Matches:

1

<span>two</span> three <span>four</span>

1

<span>two</span>

2

<span>four</span>

The greedy quantifier looks for the longest match. The non-greedy (lazy) quantifier finds the shortest match.


Ads by Google


Ask a question, send a comment, or report a problem - click here to contact me.

© Richard McGrath