Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx: Smallest possible match or nongreedy match

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

like image 239
Jonathan Allen Avatar asked Dec 17 '09 07:12

Jonathan Allen


People also ask

Which regex matches one or more digits?

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.

What does regex (? S match?

i) makes the regex case insensitive. (? s) for "single line mode" makes the dot match all characters, including line breaks.

What is lazy matching in regex?

'Lazy' means match shortest possible string. For example, the greedy h. +l matches 'hell' in 'hello' but the lazy h.

How do I match a range in regex?

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.


2 Answers

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.

like image 115
DMI Avatar answered Oct 10 '22 23:10

DMI


The non-greedy operator, ?. Like so:

.*? 
like image 34
David Hedlund Avatar answered Oct 10 '22 23:10

David Hedlund