开发者

parsing the number in the end

开发者 https://www.devze.com 2023-02-25 02:31 出处:网络
Given: Test123 Test 23 Test456 What are some ways to get the number (th开发者_如何转开发at\'s on the end) and place in an number variable?Use a RegEx like \\d+$ - this will match all the numbers at

Given:

Test123
Test 23
Test  456

What are some ways to get the number (th开发者_如何转开发at's on the end) and place in an number variable?


Use a RegEx like \d+$ - this will match all the numbers at the end of the string.


var re = new Regex(@"(\d+)$");
(new List<String>(new[]{
    "Test123",
    "Test 123",
    "Test:123"
})).ForEach(t =>
{
    var m = re.Match(t);
    Int32 n = Int32.Parse(m.Captures[0].Value);
    Console.WriteLine("{0} => Found: {1}", t, n);
});

output:

Test123 => Found: 123
Test 123 => Found: 123
Test:123 => Found: 123

Demo: http://www.ideone.com/JGgEd


Here's a way:

char[] nonZeroDigits = new char[] { '1', '2', '3', '4', '5', '6', '7', '8','9' };
int numberStart = value.IndexOfAny(nonZeroDigits);
int result = 0;
if (numberStart != -1)
    int.TryParse(value.Substring(numberStart), out result);


Just like Oded said you could do this

int i = Regex.IsMatch(input,@"\d+$") ? Convert.ToInt32(Regex.Match(input,@"\d+$").Value) : 0;


Oded's answer is good. Here is a non regex answer that uses LINQ:

string s = "Test 123";
string remainingNums = new string(s.SkipWhile(c => !Char.IsNumber(c)).ToArray());
int asInt = 0;
bool succeeded = int.TryParse(remainingNums, out asInt);


You can use Char.IsNumber method to find a number substring and then you can use int.Parse

0

精彩评论

暂无评论...
验证码 换一张
取 消