本篇文章介绍一个正则小实例,使用C#语法正则匹配字符串中的数字,提取出来。并介绍一下,C# 数字计算中的“四舍五入”。
C#正则匹配数字
一下是提取字符串中数字(包含小数)的实例代码:
string str = "优惠6.0万";
/** \\d+\\.?\\d*
* \d 表示数字
* + 表示前面的数字有一个或多个(至少出现一次)
* \. 此处需要注意,. 表示任何原子,此处进行转义,表示单纯的 小数点
* ? 表示0个或1个
* * 表示0次或者多次
*/
Regex r = new Regex("\\d+\\.?\\d*");
bool ismatch = r.IsMatch(str);
MatchCollection mc = r.Matches(str);
string result = string.Empty;
for (int i = 0; i < mc.Count; i++)
{
result += mc[i];//匹配结果是完整的数字,此处可以不做拼接的
}
Console.WriteLine(result);
// 需要注意的是,将小数点转译,这是容易忽略的
C#“四舍五入”的计算处理
C#保留一位小数,四舍五入
// result = "3.55";
// 使用Math.Round 方法
decimal d = Math.Round(Convert.ToDecimal(result), 1, MidpointRounding.AwayFromZero);
Console.WriteLine(d.ToString());
C# 从字符串中提取数字,“四舍五入”后,替换原数字
string str = "已优惠5.995万";
Regex r = new Regex("\\d+\\.?\\d*");
string result = string.Empty;
if (r.IsMatch(str))
{
MatchCollection mc = r.Matches(str);
string temp = mc.Count > 0 ? mc[0].ToString() : "";
string show = Math.Round(Convert.ToDecimal(temp), 1, MidpointRounding.AwayFromZero).ToString();
Console.WriteLine(show);
result = Regex.Replace(str, "\\d+\\.?\\d*",show);
}
else
{
result = str;
}
Console.WriteLine(result);