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

方法一、使用正则表达式

1、纯数字提取

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

2、带有小数点数字提取

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

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

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

方法二、使用ASCII码

 1 string str = "提取123abc提取";    //我们抓取当前字符当中的123
 2 foreach (char c in str)
 3     {
 4         if (Convert.ToInt32(c) >= 48 && Convert.ToInt32(c) <= 57)
 5         {
 6            sb.Append(c);
 7         }
 8     }
 9 Console.WriteLine("使用ASCII码提取");
10 Console.WriteLine(sb.ToString());

猜你喜欢

转载自blog.csdn.net/qq_21743659/article/details/131102827
今日推荐