How to extract only numbers from a string?

5

I want to extract only the numbers of a CPF that is in a string in that format;

  

111.222.333-44

You only have to return:

  

11122233344

    
asked by anonymous 15.07.2014 / 19:51

2 answers

14

I was able to:

This code worked:

String.Join("", System.Text.RegularExpressions.Regex.Split(stringAqui, @"[^\d]"))
  • ^ within a set ( [] ) means negation.
  • \d shortcut to 0-9 , that is, numbers;

In a nutshell, regex means everything that is not a number;

    
15.07.2014 / 19:56
1

Another solution:

    [TestMethod]
    public void TestGetOnlyNumbers()
    {
        Regex r = new Regex(@"\d+");            
        string result = "";
        foreach (Match m in r.Matches("111.222.333-44"))
            result += m.Value;

        Assert.AreEqual("11122233344", result);
    }

The trick is that you need to give multiple matches in number. If you use the Regex.Match method, just take the first one (111).

    
15.07.2014 / 20:19