在C#中提取字符串末尾的数字 [英] Extract number at end of string in C#

查看:2096
本文介绍了在C#中提取字符串末尾的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能是对此进行了一点分析,但是stackoverflow如何建议是返回字符串末尾包含的整数的最佳方法.

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.

到目前为止,我已经考虑过使用一个简单的循环,LINQ和regex,但是我很好奇我将从社区中得到什么方法.显然,这不是一个很难解决的问题,但可以在解决方案中分配一定的差异.

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

推荐答案

使用以下正则表达式:

\d+$

var result = Regex.Match(input, @"\d+$").Value;

或使用Stack,可能更有效:

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());

这篇关于在C#中提取字符串末尾的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆