(转)取字符串中所有数字

c# 获取字符串中的数字
///
/// 获取字符串中的数字
///
/// 字符串
/// 数字

例子1:
public static decimal GetNumber(string str)
{
    decimal result = 0;
    if (str != null && str != string.Empty)
   {
// 正则表达式剔除非数字字符(不包含小数点.)
    str = Regex.Replace(str, @"[^d.d]", "");
// 如果是数字,则转换为decimal类型
    if (Regex.IsMatch(str, @"^[+-]?d*[.]?d*$"))
    {
    result = decimal.Parse(str);
    }
}
   return result;
}

例子2:
///
/// 获取字符串中的数字
///
/// 字符串
/// 数字
public static int GetNumberInt(string str)
{
int result = 0;
if (str != null && str != string.Empty)
{
// 正则表达式剔除非数字字符(不包含小数点.)
str = Regex.Replace(str, @"[^d.d]", "");
// 如果是数字,则转换为decimal类型
if (Regex.IsMatch(str, @"^[+-]?d*[.]?d*$"))
{
result = int.Parse(str);
}
}
return result;
}

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/jiaao/archive/2008/07/09/2628982.aspx

离子3:

public string IsNum(String str)
    {
        string ss="";
        for (int i = 0; i < str.Length; i++)
        {
            if (Char.IsNumber(str, i) == true)
            {
                ss += str.Substring(i, 1);
            }
            else
            {
                if (str.Substring(i, 1) == ",")
                {
                    ss += str.Substring(i, 1);
                }
            }
        }
        return ss;
    }
Console.Write(IsNum("aaa139504928bbb11ccc,888"));//你们看下效果就知道了.

说明:

使用正则表达式的效果:

            string str1 = "Cycle Layer: 0";
            string str11 = "Cycle Nr.: 0";
            string str2 = Regex.Replace(str1, @"[^d.d]", "");//包括小数点
            string str22 = Regex.Replace(str11, @"[^dd]", "");//不包括小数点

DateTime.Now.ToLongDateString()   //日期  
DateTime.Now.ToLongTimeString()     //时间

    DateTime datetime = DateTime.Now.ToLocalTime();    //{2010-1-22 18:36:35}
            string str0 = datetime.Date.ToString();//"2010-1-22 0:00:00"
            string strf1 = DateTime.Now.ToLongDateString();  //   "2010年1月22日"
            string strf2 = DateTime.Now.ToLongTimeString();   //"18:38:32"
            DateTime str3 = datetime.Date;   //{2010-1-22 0:00:00}
            string str4 = DateTime.Now.ToShortDateString();   //"2010-1-22"

原文地址:https://www.cnblogs.com/jackping/p/3713827.html