Getting number from a string in C#

19,026

Solution 1

Use:

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

If you want to find only number which is last "entity" in the string you should use this regex:

\d+$

If you want to match last number in the string, you can use:

\d+(?!\D*\d)

Solution 2

int val = int.Parse(Regex.Match(input, @"\d+", RegexOptions.RightToLeft).Value);

Solution 3

I always liked LINQ:

var theNumber = theString.Where(x => char.IsNumber(x));    

Though Regex sounds like the native choice...

Solution 4

This code will return the integer at the end of the string. This will work better than the regular expressions in the case that there is a number somewhere else in the string.

    public int getLastInt(string line)
    {
        int offset = line.Length;
        for (int i = line.Length - 1; i >= 0; i--)
        {
            char c = line[i];
            if (char.IsDigit(c))
            {
                offset--;
            }
            else
            {
                if (offset == line.Length)
                {
                    // No int at the end
                    return -1;
                }
                return int.Parse(line.Substring(offset));
            }
        }
        return int.Parse(line.Substring(offset));
    }

Solution 5

If your number is always after the last space and your string always ends with this number, you can get it this way:

str.Substring(str.LastIndexOf(" ") + 1)
Share:
19,026
Pankaj Upadhyay
Author by

Pankaj Upadhyay

Updated on June 23, 2022

Comments

  • Pankaj Upadhyay
    Pankaj Upadhyay almost 2 years

    I am scraping some website content which is like this - "Company Stock Rs. 7100".

    Now, what i want is to extract the numeric value from this string. I tried split but something or the other goes wrong with my regular expression.

    Please let me know how to get this value.