正则表达式替换文件中的数字

时间:2010-03-31 06:22:43

标签: c# regex

文件中有很多像200 20.5 329.2 ...的数字。现在,我需要用A * 0.8替换每个数字A.是否有任何简单的方法可以根据原始值替换原始值?

最诚挚的问候,

2 个答案:

答案 0 :(得分:8)

试试这个:

String s = "This is the number 2.5. And this is 7";
s = Regex.Replace(s, @"[+-]?\d+(\.\d*)?", m => {return (Double.Parse(m.ToString())*0.8).ToString();});
// s contains "This is the number 2. And this is 5.6"

编辑:在前面添加加号/减号作为可选字符。为避免将3-5中的5分视为否定,您可以使用((?<=\s)[+-])?代替[+-]

答案 1 :(得分:0)

使用lambda并稍微更好地处理像The value is .5. Next sentence这样的案例:

var s = "This is the number 2.5. And this is 7, .5, 5. Yes.";
var result = Regex.Replace(s, @"[+-]?(\d*\.)?\d+", m => (double.Parse(m.Value) * 0.8).ToString());