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 12:55

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());
查看更多
混吃等死
3楼-- · 2019-02-11 13:04
[^0-9]+([0-9]+)

should do it I think

查看更多
【Aperson】
4楼-- · 2019-02-11 13:07

Regex would be the easiest, as far as my experience.

Regex ex = new Regex(@"(\d+)$")

This should match it. Just wrap that in a function.

查看更多
smile是对你的礼貌
5楼-- · 2019-02-11 13:11

A simple loop should probably beat any other solution in its simplicity and efficiency. And final returned string can be just copied once without usage of Stack, StringBuilder, string.Concat or other more complex string supporting functions.

string GetNumberFromEnd(string text)
{
    int i = text.Length - 1;
    while (i >= 0)
    {
        if (!char.IsNumber(text[i])) break;
        i--;
    }
    return text.Substring(i + 1);
}

Or it can be even returned back directly as int type:

bool GetIntFromEnd(string text, out int number)
{
    int i = text.Length - 1;
    while (i >= 0)
    {
        if (!char.IsNumber(text[i])) break;
        i--;
    }
    return int.TryParse(text.Substring(i + 1), out number);
}
查看更多
可以哭但决不认输i
6楼-- · 2019-02-11 13:16

Obligatory LINQ one-liner

var input = "ABCD1234";
var result = string.Concat(input.ToArray().Reverse().TakeWhile(char.IsNumber).Reverse());
查看更多
我命由我不由天
7楼-- · 2019-02-11 13:16

Is it always in the format LettersNumbers?

In that case, this would work:

Regex _cellAddressRegex = new Regex(@"(?<Column>[a-z]+)(?<Row>[0-9]+)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
var rowm = Convert.ToInt32(parts.Groups["Row"]);
查看更多
登录 后发表回答