Get last characters during character! = "_"

I have a line 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 automatic or pre-made function for this, or do I need to do this completely manually.

ASP.NET C # 4.0

+3
source share
7 answers

You can split the line with the _ character and take the last line of the result array, and then split it. character and take the first line of the result array.

in js

test.split('_')[1].split('.')[0];

CS uses the SubString and IndexOf methods for the String class.

+1
source

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

Regex.Match ("http://example.com/upload/user/80_747.jpg",   @"_(\d+)\.")
    .Groups[1]
    .Captures[0]
    .Value
+3
source
int startIndex = test.LastIndexOf('_');
int endIndex = test.LastIndexOf('.');
return test.Substring(startIndex, endIndex - startIndex);

.net4, , linq:

return new string(test.SkipWhile(x=>x!='_').Skip(1).TakeWhile(x=>x!='.').ToArray());
+2

System.IO.Path . , , . , , , , , "_".

+1

test.LastIndexOf('_'), _.

0
string val = Path.GetFileNameWithoutExtension(test.Substring(test.LastIndexOf('_') + 1));
0
test
    .ToCharArray()
    .Reverse()
    .SkipWhile(c =>
    {
        int i;
        return !int.TryParse(c.ToString(), out i);
    })
    .TakeWhile(c => c != '_');

, .

0

All Articles