您的位置:首页 > 编程语言 > C#

c# 获取字符串中的数字

2017-02-24 13:40 176 查看
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]", "");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: