RegEx: smallest match or incorrect match

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

+48
regex
Dec 17 '09 at 7:12
source share
3 answers

For a regular expression such as .* Or .+ , Add a question mark ( .*? Or .+? ) To match as few characters as possible. For optional section matching (?:blah)? but without coordination, if absolutely necessary, use something like (?:blah){0,1}? . For duplicate matches (using the {n,} or {n,m} syntax), add a question mark to try to match as little as possible (for example, {3,}? Or {5,7}? ).

Regular expression quantifier documentation can also be helpful.

+114
Dec 17 '09 at 7:15
source share

Unwanted operator ? . For example:

 .*? 
+45
Dec 17 '09 at 7:14
source share

An undesired operator does not mean the shortest match:

abcabk

a.+?k will match the entire line (in this example), and not just the last three characters.

I would like to find the smallest possible match.

This is that the last possible match for ' a ' should allow all matches for k .

I guess the only way to do this is to use an expression like:

 a[^a]+?k 
+17
Jan 31 '14 at 11:22
source share



All Articles