I need to get only the last number from the string. The string contains pattern of string+integer+string+integer i.e. "GS190PA47". I need to get only 47 from the string.
Thank you
I need to get only the last number from the string. The string contains pattern of string+integer+string+integer i.e. "GS190PA47". I need to get only 47 from the string.
Thank you
Try this:
string input = "GS190PA47";
Regex r = new Regex(@"\d+\D+(\d+)");
int number = int.Parse(r.Match(input).Groups[1].Value);
Pattern means we find set of digits (190), next set of non-digit chars (PA) and finally sought-for number.
Don't forget include using System.Text.RegularExpressions directive.
Not sure if this is less or more efficient than RegEx (Profile it)
string input = "GS190PA47";
var x = Int32.Parse(new string(input.Where(Char.IsDigit).ToArray()));
Amazingly it is actually much faster than regex
var a = Stopwatch.StartNew();
for (int i = 0; i < 10000; i++)
{
string input = "GS190PA47";
var x = Int32.Parse(new string(input.Reverse().TakeWhile(Char.IsDigit).Reverse().ToArray()));
}
a.Stop();
var b = a.ElapsedMilliseconds;
Console.WriteLine(b);
a = Stopwatch.StartNew();
for (int i = 0; i < 10000; i++)
{
string input = "GS190PA47";
var x = Int32.Parse(Regex.Matches(input, @"\d+").Cast<Match>().Last().Value);
}
a.Stop();
b = a.ElapsedMilliseconds;
Console.WriteLine(b);