试图用Regex获取URL的最后一部分

Cal*_*res 5 c# regex

这是我到目前为止:

string s = @"http://www.s3.locabal.com/whatever/bucket/folder/guid";
string p = @".*//(.*)";
var m = Regex.Match(s, p);
Run Code Online (Sandbox Code Playgroud)

但是,这会回来"www.s3.locabal.com/whatever/bucket/folder/guid".

SLa*_*aks 16

使用Uri该类来解析URL:

new Uri(s).Segments.Last()
Run Code Online (Sandbox Code Playgroud)


pok*_*oke 13

虽然Uri.Segments可能是最好的方法,但这里有一些选择:

string s = "http://www.s3.locabal.com/whatever/bucket/folder/guid";

// Uri
new Uri(s).Segments.Last();

// string
s.Substring(s.LastIndexOf("/") + 1);

// RegExp
Regex.Match(s, ".*/([^/]+*)$").Groups[1];
Run Code Online (Sandbox Code Playgroud)