Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Match with Regex "shortest match" in .NET

Tags:

c#

.net

regex

I'm facing a problem with Regex... I had to match sharepoint URL.. I need to match the "shortest"

Something like:

http://aaaaaa/sites/aaaa/aaaaaa/

m = Regex.Match(URL, ".+/sites/.+/");

m.Value equals to the whole string...

How can I make it match

http://aaaaaaa/sites/aaaa/

and nothing else??

Thank you very much!

like image 200
Ziba Leah Avatar asked Apr 10 '12 17:04

Ziba Leah


2 Answers

.+ is greedy, so it will match as many characters as possible before stopping. Change it to .+? and the match will end as soon as possible:

m = Regex.Match(URL, ".+/sites/.+?/");
like image 86
Andrew Clark Avatar answered Sep 20 '22 08:09

Andrew Clark


Try making the regex matching everything but a / instead of simply everything. This is done by using the not form of the character class atom [^].

m = Regex.Match(URL, ".+/sites/[^/]+/");
like image 43
JaredPar Avatar answered Sep 20 '22 08:09

JaredPar