How do I tell RegEx (.NET version) to get the smallest valid match instead of the largest?
+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
2009-12-17 07:15:02
That is exactly what I needed to know.
Jonathan Allen
2009-12-19 18:00:50