Getting a number from a string in C #

I am clearing the content of the website that looks like this: Stock Rs. 7100 Company .

Now I want to extract a numeric value from this string. I tried split but something or other is wrong with my regex.

Please let me know how to get this value.

+3


source to share


7 replies


Using:

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

      

If you only want to find the number that is the last "entity" in the string, you must use this regular expression:



\d+$

      

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

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

      

+13


source


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

      



+4


source


I've always liked LINQ

:

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

      

Although it Regex

sounds like its own choice ...

+2


source


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

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

      

+1


source


If your number is always after the last space, and your line always ends with that number, you can get it like this:

str.Substring(str.LastIndexOf(" ") + 1)

      

+1


source


Here is my answer .... it separates numeric strings from string using C # ....

    static void Main(string[] args)
    {
        String details = "XSD34AB67";
        string numeric = "";
        string nonnumeric = "";
        char[] mychar = details.ToCharArray();
        foreach (char ch in mychar)
        {
            if (char.IsDigit(ch))
            {

                numeric = numeric + ch.ToString();
            }
            else
            {
                nonnumeric = nonnumeric + ch.ToString();
            }
        }

        int i = Convert.ToInt32(numeric);
        Console.WriteLine(numeric);
        Console.WriteLine(nonnumeric);
        Console.ReadLine();



    }
}

      

}

+1


source


You can use \d+

to match the first occurrence of a number:

string num = Regex.Match(input, @"\d+").Value;

      

0


source







All Articles