-1

我正在尝试从 C# 中的 URL 获取字符串。URL 将如下所示:

http://www.somesite.com/something/I-WANT-THIS-SEGMENT/cms/somethingelse

或者

http://www.somesite.com/something/someotherthing/I-WANT-THIS-SEGMENT/cms

或者

http://www.somesite.com/I-WANT-THIS-SEGMENT/cms/something

基本上,我想要“cms”之前的段

4

1 回答 1

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正如 George 指出的那样,使用这个类也很好。

于 2012-09-04T14:00:28.730 回答