[数据库][C#]提取字符串中的数字

1 /// <summary>
2 /// 去掉字符串中的数字
3 /// </summary>
4 /// <param name="str"></param>
5 /// <returns></returns>
6 public static string RemoveNumber(string str)
7 {
8     return System.Text.RegularExpressions.Regex.Replace(str, @"d", "");
9 }
1 /// <summary>
2 /// 去掉字符串中的非数字
3 /// </summary>
4 /// <param name="key"></param>
5 /// <returns></returns>
6 public static string RemoveNonNumber(string str)
7 {
8     return System.Text.RegularExpressions.Regex.Replace(str, @"[^d]*", "");
9 }

实测发现上述两个方法不稳定,有时成功有时失败!!!不可取!!!

作为代替,以下方法实测有效,稳定性也很好,推荐使用:

 1 public string ExtractNumber(string str)
 2         {
 3             string strNumber = "";
 4             MatchCollection ms = Regex.Matches(str, @"d+");
 5             foreach (Match m in ms)
 6             {
 7                strNumber += m.Value;
 8             }
 9             return strNumber;
10         }
11 
12 
13 
14 public static IList<string> ExtractString(string str)
15 {
16     IList<string> strList=new List<string>();
17     MatchCollection ms = Regex.Matches(str, @"D+");
18     foreach(Match m in ms)
19     {
20        strList.Add(m.Value);
21     }
22     return strList;
23 }
原文地址:https://www.cnblogs.com/avin/p/6896213.html