Extract number at end of string in C#
Use this regular expression:
\d+$
var result = Regex.Match(input, @"\d+$").Value;
or using Stack
, probably more efficient:
var stack = new Stack<char>();
for (var i = input.Length - 1; i >= 0; i--)
{
if (!char.IsNumber(input[i]))
{
break;
}
stack.Push(input[i]);
}
var result = new string(stack.ToArray());
Obligatory LINQ one-liner
var input = "ABCD1234";
var result = string.Concat(input.ToArray().Reverse().TakeWhile(char.IsNumber).Reverse());
Regex pattern like \d+$
is a bit expensive since, by default, a string is parsed from left to right. Once the regex engine finds 1
in 12abc34
, it goes on to match 2
, and when it encounters a
, the match is failed, next position is tried, and so on.
However, in .NET regex, there is a RegexOptions.RightToLeft
modifier. It makes the regex engine parse the string from right to left and you may get matches that are known to be closer to the end much quicker.
var result = Regex.Match("000AB22CD1234", @"\d+$", RegexOptions.RightToLeft);
if (result.Success)
{
Console.Write(result.Value);
} // => 1234
See the online C# demo.