Muhammad Adnan
Muhammad Adnan

Reputation: 1403

Regex to get NUMBER only from String

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;

Upvotes: 85

Views: 275359

Answers (3)

bluetoft
bluetoft

Reputation: 5443

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

Upvotes: 158

Joey
Joey

Reputation: 354466

Either [0-9] or \d1 should suffice if you only need a single digit. Append + if you need more.


1 The semantics are slightly different as \d potentially matches any decimal digit in any script out there that uses decimal digits.

Upvotes: 6

Kobi
Kobi

Reputation: 138007

\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+"

Upvotes: 93

Related Questions