的构成电脑 | 电脑由什么构成
682 2023-04-02 20:20:02
下面讲解如何在字符串当中抓取到数字
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 }
Regex.IsMatch(str, @"^([01](.0+)?|0.[0-9]+)$")
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());