Thursday, February 14, 2008

Non-Greedy Regular Expression Matching

This applies to Ruby, and many other languages too (eg. Perl), just that I keep forgetting it. In order to have non-greedy matching enabled, append the question mark after the quantifiers, ie.


* (0 or more) greedy matching
+ (1 or more) greedy matching
*? (0 or more) non-greedy matching
+? (1 or more) non-greedy matching


For vim, the syntax is slightly more convoluted, so it's important to put a note here for my own reminder:


* (0 or more) greedy matching
\+ (1 or more) greedy matching
\{-} (0 or more) non-greedy matching
\{-n,} (at least n) non-greedy matching


There's no direct '(1 or more) non-greedy matching' in vim, but the 'at least n' operation should be the equivalent. For vim, these should normally be default and independent of whether if the 'very magic' or 'very nomagic' mode is set. See help in pattern.txt, for more pattern matching details.

2 comments:

Robyurkowski said...

Very helpful! Thanks, belatedly!

Anonymous said...

Once I found this page I needed it twice the same day : one time for perl, the other for vi !

Post a Comment