C# 如何提取字符串中的数字

下面讲解如何在字符串当中抓取到数字

方法一、使用正则表达式

1、纯数字提取

 string str = "提取123abc提取";    //我们抓取当前字符当中的123
string result = System.Text.RegularExpressions.Regex.Replace(str, @"[^0-9]+", "");
Console.WriteLine("使用正则表达式提取数字");
Console.WriteLine(result);

2、带有小数点数字提取

 string str = "提取123.11abc提取"; //我们抓取当前字符当中的123.11
str=Regex.Replace(str, @"[^\d.\d]", "");
// 如果是数字,则转换为decimal类型
if (Regex.IsMatch(str, @"^[+-]?\d*[.]?\d*$"))
{
decimal result = decimal.Parse(str);
Console.WriteLine("使用正则表达式提取数字");
Console.WriteLine(result);
}

3、提取大于等于0,小于等于1的数字

Regex.IsMatch(str, @"^([01](\.0+)?|0\.[0-9]+)$")

方法二、使用ASCII码

 string str = "提取123abc提取";    //我们抓取当前字符当中的123
foreach (char c in str)
{
if (Convert.ToInt32(c) >= && Convert.ToInt32(c) <= )
{
sb.Append(c);
}
}
Console.WriteLine("使用ASCII码提取");
Console.WriteLine(sb.ToString());

C# 如何提取字符串中的数字

PS:如有疑问,请留言,未经允许,不得私自转载,转载请注明出处:http://www.cnblogs.com/xuliangxing/p/7993267.html

  C# 如何提取字符串中的数字

上一篇:【Matplotlib】设置刻度(1)


下一篇:jetty demo实例启动