C#正则表达式查找所有数字并将它们四舍五入到小数点后两位

时间:2018-08-22 07:48:56

标签: c# regex numbers

我正在尝试清理使用c#发送的状态电子邮件,该电子邮件包含许多数字,这些数字最多可以有8或9个小数位。我如何找到所有数字并将其替换为自己的舍入版本?

我想到的第一种方法是使用正则表达式找到它们,然后将它们一个个替换,但是有没有办法使用带有两种模式的regex.replace来做到这一点?

1 个答案:

答案 0 :(得分:2)

我认为您想使用MatchEvaluator参数或Regex.Replace。它需要一个代表根据每个特定的匹配来选择您的替代者。 像这样:

var data = ""

//Just a sample pattern for decimal numbers
var pattern = @"^[0-9]([.,][0-9]{1,9})?$";

var Matches = Regex.Replace(data, pattern, (m) =>
{
    //double.Parse your m.ToString in here, round it up or down, then convert it back 
    //to a string and return that
});