C# 如何提取字符串中的数字(小技巧)

您所在的位置:网站首页 字符串中字母个数 C# 如何提取字符串中的数字(小技巧)

C# 如何提取字符串中的数字(小技巧)

2024-07-11 10:49| 来源: 网络整理| 查看: 265

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

方法一、使用正则表达式

1、纯数字提取

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

多个数字值

 

string str = "提取123abc提取234234234";      string r = @"[0-9]+"; Regex reg = new Regex(r, RegexOptions.IgnoreCase | RegexOptions.Singleline, TimeSpan.FromSeconds(2));//2秒后超时 MatchCollection mc = reg.Matches(str);//设定要查找的字符串 foreach (Match m in mc) { string s = m.Groups[0].Value; }

 

 

 

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)


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3