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

依然范特西╮ 提交于 2019-11-28 08:59:59

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)

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