Best way to get all digits from a string

Chris Marisic picture Chris Marisic · Apr 14, 2010 · Viewed 34.8k times · Source

Is there any better way to get take a string such as "(123) 455-2344" and get "1234552344" from it than doing this:

var matches = Regex.Matches(input, @"[0-9]+", RegexOptions.Compiled);

return String.Join(string.Empty, matches.Cast<Match>()
                                .Select(x => x.Value).ToArray());

Perhaps a regex pattern that can do it in a single match? I couldn't seem to create one to achieve that though.

Answer

Matt Hamilton picture Matt Hamilton · Apr 14, 2010

Do you need to use a Regex?

return new String(input.Where(Char.IsDigit).ToArray());