Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get last characters while character != "_"

Tags:

string

c#

asp.net

I have string like

string test = "http://example.com/upload/user/80_747.jpg"
string test2 = "http://example.com/upload/user/80_4747.jpg"

In both cases i need "747" or "4747". Is there any auto or pre-made function for this or i need to do it fully manual.

ASP.NET C# 4.0

like image 824
Novkovski Stevo Bato Avatar asked Nov 26 '25 06:11

Novkovski Stevo Bato


2 Answers

Regular expression should work fine for this. Something like @"_(\d+)\.".

Regex.Match ("http://example.com/upload/user/80_747.jpg",   @"_(\d+)\.")
    .Groups[1]
    .Captures[0]
    .Value
like image 112
Alexei Levenkov Avatar answered Nov 27 '25 19:11

Alexei Levenkov


int startIndex = test.LastIndexOf('_');
int endIndex = test.LastIndexOf('.');
return test.Substring(startIndex, endIndex - startIndex);

Since you're using .net4, and if your string format is as stated now, you can do it with linq:

return new string(test.SkipWhile(x=>x!='_').Skip(1).TakeWhile(x=>x!='.').ToArray());
like image 43
Saeed Amiri Avatar answered Nov 27 '25 18:11

Saeed Amiri