C# 如何提取字符串中的數字
阿新 • • 發佈:2017-12-06
image .cn pan 疑問 asc eight ole size tar
下面講解如何在字符串當中抓取到數字
方法一、使用正則表達式
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 }
方法二、使用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());
PS:如有疑問,請留言,未經允許,不得私自轉載,轉載請註明出處:http://www.cnblogs.com/xuliangxing/p/7993267.html
C# 如何提取字符串中的數字