29

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.

Chris Marisic
  • 32,487
  • 24
  • 164
  • 258

5 Answers5

88

Do you need to use a Regex?

return new String(input.Where(Char.IsDigit).ToArray());
Matt Hamilton
  • 200,371
  • 61
  • 386
  • 320
24

Have you got something against Replace?

return Regex.Replace(input, @"[^0-9]+", "");
Alan Moore
  • 73,866
  • 12
  • 100
  • 156
11

You'll want to replace /\D/ (non-digit) with '' (empty string)

Regex r = new Regex(@"\D");
string s = Regex.Replace("(123) 455-2344", r, "");

Or more succinctly:

string s = Regex.Replace("(123) 455-2344", @"\D",""); //return only numbers from string
grant7bar7
  • 118
  • 1
  • 4
maček
  • 76,434
  • 37
  • 167
  • 198
  • I like this answer. However, between this one and the accepted answer, are there significant difference beside one using Regex and another isn't? – frostshoxx Oct 08 '20 at 23:06
7

Just remove all non-digits:

var result = Regex.Replace(input, @"\D", "");
Konstantin Spirin
  • 20,609
  • 15
  • 72
  • 90
0

In perl (you can adapt this to C#) simply do

$str =~ s/[^0-9]//g; 

I am assuming that your string is in $str. Basic idea is to replace all non digits with '' (i.e. empty string)

Prix
  • 19,417
  • 15
  • 73
  • 132
Jasmeet
  • 2,324
  • 16
  • 9