Question
I have the following string:
$/Mycollection/Branches/Dev/New/php/MySite/src/MySite/somefolder/src/sad.php
I need to create regex pattern and take everything before first appearance of "src".
I've tried to use like that .+(src)
but as I understood I need to decrease greed, could anyone help ?
Solution
You're close. You can just do this...
(^.+?)src
Then get the value of the first group captured.
You can also do this another way...
src.+
Then replace the match with ""
.
For example (in C#) ...
string value = Regex.Replace(yourstring, "src.+", "");
It's actually much more efficient to use this method. It'll do around 1 million iterations per second vs 150,000 iterations per second for the first method (at least in .NET). That's partly because there's some overhead in using capturing groups, and partly because of the backtracking that occurs with the lazy ?
quantifier.
By the way, I did the testing and benchmarking with Regex Hero and then here's a good article that covers the lazy ?
quantifier.
OTHER TIPS
You can use this regex: (.*?)src
and use the first captured group only.
In some modern regex implementations, .+?
is stingy, i e. add a question mark after a greedy quantifier to change it to stingy.