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

我只是一个虾纸丫 提交于 2019-11-27 02:33:27

问题


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.


回答1:


Do you need to use a Regex?

return new String(input.Where(Char.IsDigit).ToArray());



回答2:


Have you got something against Replace?

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



回答3:


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



回答4:


Just remove all non-digits:

var result = Regex.Replace(input, @"\D", "");



回答5:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!