Extract numbers from string to create digit only string

56,242

Solution 1

Not familiar enough with .NET for exact code. Nonetheless, two approaches would be:

  • Cast it as an integer. If the non-digit characters are at the end (i.e. 21389abc), this is the easiest.
  • If you have intermixed non-digit characters (i.e. 1231a23v) and want to keep every digit, use the regex [^\d] to replace non-digit characters.

Solution 2

You could write a simple method to extract out all non-digit characters, though this won't handle floating point data:

public string ExtractNumber(string original)
{
     return new string(original.Where(c => Char.IsDigit(c)).ToArray());
}

This purely pulls out the "digits" - you could also use Char.IsNumber instead of Char.IsDigit, depending on the result you wish.

Solution 3

Try this oneliner:

Regex.Replace(str, "[^0-9 _]", "");

Solution 4

You can use a simple regular expression:

var numericPart = Regex.Match( a, "\\d+" ).Value;

If you need it to be an actual numeric value, you can then use int.Parse or int.TryParse.

Solution 5

You could use LINQ. The code below filters the string into an IEnumerable with only digits and then converts it to a char[]. The string constructor can then convert the char[] into a string:

string a = "557222]]>";
string b = "5100870<br>";

a = new string(a.Where(x => char.IsDigit(x)).ToArray());
b = new string(b.Where(x => char.IsDigit(x)).ToArray());
Share:
56,242
kevp
Author by

kevp

Working with GIS, building mapping software!

Updated on July 05, 2022

Comments

  • kevp
    kevp almost 2 years

    I have been given some poorly formatted data and need to pull numbers out of strings. I'm not sure what the best way to do this is. The numbers can be any length.

    string a = "557222]]>";
    string b = "5100870<br>";
    

    any idea what I can do so I'll get this:

    a = "557222"
    b = "5100870"
    

    Thanks

    Solution is for c# sorry. Edited the question to have that tag