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
  • 31,683
  • 22
  • 160
  • 255

5 Answers5

85

Do you need to use a Regex?

return new String(input.Where(Char.IsDigit).ToArray());
Matt Hamilton
  • 194,622
  • 60
  • 382
  • 318
23

Have you got something against Replace?

return Regex.Replace(input, @"[^0-9]+", "");
Alan Moore
  • 71,299
  • 12
  • 93
  • 154
10

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
  • 73,409
  • 36
  • 162
  • 195
  • 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
6

Just remove all non-digits:

var result = Regex.Replace(input, @"\D", "");
Konstantin Spirin
  • 19,394
  • 14
  • 66
  • 88
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,173
  • 14
  • 69
  • 128
Jasmeet
  • 2,254
  • 16
  • 9