如何匹配与正则表达式"最短的匹配"在.NET最短、正则表达式、QUOT、NET

2023-09-04 00:31:29 作者:挥刀斩情丝

我现在面临一个问题,正则表达式......我必须匹配的SharePoint URL。我需要匹配的最短

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

是这样的:

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

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

m.Value等于整个字符串...

m.Value equals to the whole string...

我怎样才能使其匹配

http://aaaaaaa/sites/aaaa/

和没有别的?

非常感谢你!

推荐答案

+ 是贪婪的,所以它会停止之前匹配尽可能多的字符可能。 ?将其更改为 + 和比赛将尽快结束,因为可能的:

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