Sublime Forum

Non-greedy regex not so all the time

#1

Say I have following line in my file:
[ "$(${Git} branch --show-current)" != "master" ] && ${Git} checkout -f "${branch}"
When I use regex git.*?checkout it selects following portion:
Git} branch --show-current)" != "master" ] && ${Git} checkout
and not
Git} checkout

0 Likes

#2

Maybe not what you expect, but still correct.

.*? does not provide any restrictions for content between git and checkout. So the engine finds first git and than lazily looks for the next occurance of checkout.

The question mark would make a difference in case checkout appeared multiple times.

Example:

[ "$(${Git} branch --show-current)" != "master" ] && ${Git} checkout -f "${checkout}"

pattern result
git.*?checkout Git} branch --show-current)" != "master" ] && ${Git} checkout
git.*checkout [ "$(${Git} branch --show-current)" != "master" ] && ${Git} checkout -f "${checkout

You can double check it agains various regex engines at https://regex101.com/

0 Likes

#3

Thanks, I settled with .*\Kgit.*?checkout for now :slight_smile:

0 Likes