How do I tell RegEx (.NET version) to get the smallest valid match instead of the largest?
Occurrence Indicators (or Repetition Operators): +: one or more ( 1+ ), e.g., [0-9]+ matches one or more digits such as '123' , '000' . *: zero or more ( 0+ ), e.g., [0-9]* matches zero or more digits. It accepts all those in [0-9]+ plus the empty string.
i) makes the regex case insensitive. (? s) for "single line mode" makes the dot match all characters, including line breaks.
'Lazy' means match shortest possible string. For example, the greedy h. +l matches 'hell' in 'hello' but the lazy h.
The regex [0-9] matches single-digit numbers 0 to 9. [1-9][0-9] matches double-digit numbers 10 to 99. Something like ^[2-9][1-6]$ matches 21 or even 96! Any help would be appreciated.
For a regular expression like .*
or .+
, append a question mark (.*?
or .+?
) to match as few characters as possible. To optionally match a section (?:blah)?
but without matching unless absolutely necessary, use something like (?:blah){0,1}?
. For a repeating match (either using {n,}
or {n,m}
syntax) append a question mark to try to match as few as possible (e.g. {3,}?
or {5,7}?
).
The documentation on regular expression quantifiers may also be helpful.
The non-greedy operator, ?
. Like so:
.*?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With