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]", "");
