85

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;

3 Answers 3

158

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
Sign up to request clarification or add additional context in comments.

1 Comment

Regex.Replace(input, @"\D", "");
93

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

Comments

6

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.

4 Comments

please define exact regex to use in Regex.Match function.... Because i m not good in Regex (SYNTAX)
For a single digit you don't need a regex: char digit = s.First(Char.IsDigit);. I'd add that to my answer, but I don't think that's the case here.
@Kobi: That would still need explicit iteration over the string, though. Most people opting to use regex wouldn't want to do this :-)
@MuhammadAdnan, var newInput = Regex.Replace(input, @"[^\d]", "");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.