Ziba Leah
Ziba Leah

Reputation: 2514

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

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!

Upvotes: 18

Views: 9837

Answers (2)

Andrew Clark
Andrew Clark

Reputation: 208555

.+ 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/.+?/");

Upvotes: 38

JaredPar
JaredPar

Reputation: 755141

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/[^/]+/");

Upvotes: 8

Related Questions