Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to get NUMBER only from String

Tags:

c#

regex

I recieve "7+" or "5+" or "+5" from XML and wants to extract only the number from string using Regex. e.g Regex.Match() function

        stringThatHaveCharacters = stringThatHaveCharacters.Trim();         Match m = Regex.Match(stringThatHaveCharacters, "WHAT I USE HERE");         int number = Convert.ToInt32(m.Value);         return number; 
like image 927
Muhammad Adnan Avatar asked Jan 25 '11 10:01

Muhammad Adnan


People also ask

How do I select only numbers in regex?

If you want to get only digits using REGEXP, use the following regular expression( ^[0-9]*$) in where clause. Case 1 − If you want only those rows which have exactly 10 digits and all must be only digit, use the below regular expression.

How do I find an integer from a string in regex?

Python Regex – Get List of all Numbers from String. To get the list of all numbers in a String, use the regular expression '[0-9]+' with re. findall() method. [0-9] represents a regular expression to match a single digit in the string.

How do you find a number in a string?

To find whether a given string contains a number, convert it to a character array and find whether each character in the array is a digit using the isDigit() method of the Character class.


2 Answers

\d+

\d represents any digit, + for one or more. If you want to catch negative numbers as well you can use -?\d+.

Note that as a string, it should be represented in C# as "\\d+", or @"\d+"

like image 34
Kobi Avatar answered Sep 22 '22 02:09

Kobi


The answers above are great. If you are in need of parsing all numbers out of a string that are nonconsecutive then the following may be of some help:

string input = "1-205-330-2342"; string result = Regex.Replace(input, @"[^\d]", ""); Console.WriteLine(result); // >> 12053302342 
like image 54
bluetoft Avatar answered Sep 19 '22 02:09

bluetoft