Best way to get all digits from a string [duplicate]
Asked Answered
D

5

31

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.

Discus answered 14/4, 2010 at 3:36 Comment(0)
D
89

Do you need to use a Regex?

return new String(input.Where(Char.IsDigit).ToArray());
Doriadorian answered 14/4, 2010 at 3:45 Comment(8)
+1, good idea. You left out a bit of the lambda inside the where, though. .Where(c => Char.IsDigit(c))Jaclin
Didn't consider approaching this from the char level.Discus
@Anthony No, my syntax works fine, and is less "noisy" than the expanded version.Doriadorian
Oh, interesting. I had not tried it that way.Jaclin
Upvote for "Do you need to use a Regex" :DBedroll
does this handle floating point and negative numbers?Overhang
@BKSpurgeon No, char.IsDigit('.') and char.IsDigit('-') both return false.Chester
Hell yeah my man, Screw regex :)Colonel
L
25

Have you got something against Replace?

return Regex.Replace(input, @"[^0-9]+", "");
Lignite answered 14/4, 2010 at 3:49 Comment(0)
H
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
Hose answered 14/4, 2010 at 3:48 Comment(1)
I like this answer. However, between this one and the accepted answer, are there significant difference beside one using Regex and another isn't?Fowle
L
7

Just remove all non-digits:

var result = Regex.Replace(input, @"\D", "");
Lark answered 14/4, 2010 at 5:45 Comment(0)
B
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)

Bethesde answered 14/4, 2010 at 6:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.