How can I delete all the non-numerical chars from a string and get the numerics only as a new string?
I have a long string witn many charaters like :
"8798dsfgsd98gs87£%"%001912.43.36."
How can I开发者_StackOverflow社区 delete all the non-numerical chars and get the numerics so that I can get:
"879898870019124336"
in C# ?
Thanks
var text = "8798dsfgsd98gs87£%"%001912.43.36.";
var numText = new string( text.Where(c=>char.IsDigit(c)).ToArray() );
EDIT:
If your goal is performance, use StringBuilder
:
var text = "8798dsfgsd98gs87£%"%001912.43.36.";
var numText = new StringBuilder();
for(int i = 0; i < text.Length; i++) {
char c = text[i];
if ( char.IsDigit(c) ) {
numText.Append(c);
}
}
string text = "8798dsfgsd98gs87£%\"%001912.43.36.";
string digits = Regex.Replace(text, "[^0-9]", ""); // "879898870019124336"
Regex answer...
using System.Text.RegularExpressions;
private string justNumeric(string str)
{
Regex rex = new Regex(@"[^\d]");
return rex.Replace(str,"");
}
string str = "8798dsfgsd98gs87£%%001912.43.36.";
string result = string.Empty;
for (int j = 0; j < str.Length; j++)
{
int i;
try
{
i = Convert.ToInt16(str[j].ToString());
result += i.ToString();
}
catch { }
}
Try this way.....
Another regex answer;
string str = "8798dsfgsd98gs87£%%001912.43.36.";
string justNumbers = new Regex(@"\D").Replace(str,"");
精彩评论