Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to get the last part of a URL with Regex

Tags:

c#

regex

This is what I have so far:

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

However, this returns "www.s3.locabal.com/whatever/bucket/folder/guid".

like image 741
Caleb Jares Avatar asked Nov 13 '12 22:11

Caleb Jares


2 Answers

Use the Uri class to parse URLs:

new Uri(s).Segments.Last()
like image 78
SLaks Avatar answered Oct 19 '22 23:10

SLaks


Although Uri.Segments is probably the best way to do it, here are some alternatives:

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];
like image 33
poke Avatar answered Oct 19 '22 23:10

poke