c# 获取字符串中的数字

x

        /// <summary>
        /// 获取字符串中的数字 
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>数字</returns>
        public static decimal GetNumber(string str)
        {
            decimal result = 0;
            if (str != null && str != string.Empty)
            {
                // 正则表达式剔除非数字字符(不包含小数点.)
                //str = Regex.Replace(str, @"[^/d./d]", "");
          str = Regex.Replace(str, @"[^d.d]", "");
// 如果是数字,则转换为decimal类型 if (Regex.IsMatch(str, @"^[+-]?d*[.]?d*$")) { result = decimal.Parse(str); } } return result; } /// <summary> /// 获取字符串中的数字 /// </summary> /// <param name="str">字符串</param> /// <returns>数字</returns> 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; }

x

→原文链接←

x

对原文的修改:

str = Regex.Replace(str, @"[^/d./d]", "");
//修改:"/"修改为""
str = Regex.Replace(str, @"[^d.d]", "");
原文地址:https://www.cnblogs.com/love-zf/p/6438227.html