tags:

views:

85

answers:

5

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.

+5  A: 

Do you need to use a Regex?

return new String(input.Where(Char.IsDigit).ToArray());
Matt Hamilton
+1, good idea. You left out a bit of the lambda inside the where, though. `.Where(c => Char.IsDigit(c))`
Anthony Pegram
Didn't consider approaching this from the char level.
Chris Marisic
@Anthony No, my syntax works fine, and is less "noisy" than the expanded version.
Matt Hamilton
@Matt - Oh, interesting. I had not tried it that way.
Anthony Pegram
+3  A: 

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");
macek
+4  A: 

Have you got something against Replace?

return Regex.Replace(input, @"[^0-9]+", "");
Alan Moore
A: 

Just remove all non-digits:

var result = Regex.Replace(input, @"\D", "");
Konstantin Spirin
A: 

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)

Jasmeet