tags:

views:

79

answers:

2

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

+8  A: 

The non-greedy operator, ?. Like so:

.*?
David Hedlund
+4  A: 

If you have something like .* or .+ in your regular expression, you just need to add a question mark (.*? or .+?) to match as few characters as possible. If you want to optionally match a section (?:blah)? but you want to avoid matching it unless absolutely necessary, you could use something like (?:blah){0,1}?. If you've got a repeating match (either using {n,} or {n,m} syntax) then just add a question mark afterwards to try to match as few as possible (e.g. {3,}? or {5,7}?).

If it's more complex, then could you please provide an example?

The documentation on regular expression quantifiers may also be helpful.

Dave
That is exactly what I needed to know.
Jonathan Allen