This question already has an answer here:
- return only Digits 0-9 from a String 7 answers
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.
Do you need to use a Regex?
return new String(input.Where(Char.IsDigit).ToArray());
Have you got something against Replace
?
return Regex.Replace(input, @"[^0-9]+", "");
maček
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
Just remove all non-digits:
var result = Regex.Replace(input, @"\D", "");
Jasmeet
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)
来源:https://stackoverflow.com/questions/2634731/best-way-to-get-all-digits-from-a-string