The above example returns the "leftmost longest" match. Likewise, this example returns the rightmost match:
'looool lool lol loool'.match(/.*(lo+?l)/)[1]
// => 'loool'
But i'm curious of a solution to match the shortest "lol" possible.
The above example returns the "leftmost longest" match. Likewise, this example returns the rightmost match:
'looool lool lol loool'.match(/.*(lo+?l)/)[1]
// => 'loool'
But i'm curious of a solution to match the shortest "lol" possible.
There isn't a regex metaquantifier that lets you ask for the shortest match overall. "Leftmost" trumps length considerations, whether greedy or not:
'lol looool lool lol loool'.match(/(lo+l)/)[1]
//=> "lol"
You can modify your "rightmost" version by making the prefix part non-greedy, but that still doesn't get what you want:
'looool lool lol loool'.match(/.*?(lo+?l)/)[1]
//=> "looool"
'looool lool lol loool'.match(/.+?(lo+?l)/)[1]
//=> "lool"
You really need to use logic outside of the regex to minimize the length. In Ruby, you can do this:
'looool lool lol loool'.scan(/lo+l/).min_by(&:length)
# => "lol"
Javascript makes you work a little harder:
'looool lool lol loool'.match(/lo+l/g).reduce(
function(shortest, next) {
return (!shortest || (next.length < shortest.length)) ? next : shortest;
});
//=> "lol"
But the same basic idea is likely what you'll need to do whatever your target language is.