我正在尝试从C#中的URL获取字符串。 URL将如下所示:
http://www.somesite.com/something/I-WANT-THIS-SEGMENT/cms/somethingelse
OR
http://www.somesite.com/something/someotherthing/I-WANT-THIS-SEGMENT/cms
OR
http://www.somesite.com/I-WANT-THIS-SEGMENT/cms/something
基本上,我想要在“cms”之前的片段
答案 0 :(得分:1)
不太好看,但我认为你不需要正则表达式:
string Url1 = @"http://www.somesite.com/something/I-WANT-THIS-SEGMENT/cms/somethingelse";
string Url2 = @"http://www.somesite.com/something/someotherthing/I-WANT-THIS-SEGMENT/cms";
string Url3 = @"http://www.somesite.com/I-WANT-THIS-SEGMENT/cms/something";
Url1 = Url1.Substring(0, Url1.IndexOf("/cms"));
string PartOfUrl1 = Url1.Substring(Url1.LastIndexOf("/")+1);
Console.WriteLine(PartOfUrl1);
Url2 = Url2.Substring(0, Url2.IndexOf("/cms"));
string PartOfUrl2 = Url2.Substring(Url2.LastIndexOf("/")+1);
Console.WriteLine(PartOfUrl2);
Url3 = Url3.Substring(0, Url3.IndexOf("/cms"));
string PartOfUrl3 = Url3.Substring(Url3.LastIndexOf("/")+1);
Console.WriteLine(PartOfUrl3);
使用Uri
类也很好,正如乔治所指出的那样。