Extract number at end of string in C#

2019-02-11 12:41发布

Probably over analysing this a little bit but how would stackoverflow suggest is the best way to return an integer that is contained at the end of a string.

Thus far I have considered using a simple loop, LINQ and regex but I'm curious what approaches I'll get from the community. Obviously this isn't a hard problem to solve but could have allot of variance in the solutions.

So to be more specific, how would you create a function to return an arbitrarily long integer/long that is appended at the end of an arbitrarily long string?

CPR123 => 123
ABCDEF123456 => 123456

8条回答
贼婆χ
2楼-- · 2019-02-11 13:21

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.

查看更多
▲ chillily
3楼-- · 2019-02-11 13:21

Am I allowed to go crazy with this?

using System.Text;
using System.Linq;

static string GetNum(string input)
{
    StringBuilder sb = new StringBuilder();
    for (int i = input.Length - 1; i >= 0; i--)
    {
        if (input[i] < 48 || input[i] > 57)
            break;

        sb.Append(input[i]);
    }

    return String.Concat(sb.ToString().ToCharArray().Reverse());
}
查看更多
登录 后发表回答