There are a lot of numbers like 200 20.5 329.2...in a file. Now, I need replace every number A with A*0.8. Is there any simple method to replace original value with another based on original value?
在文件中有很多像200 20.5 329.2 ...的数字。现在,我需要用A * 0.8替换每个数字A.是否有任何简单的方法可以根据原始值替换原始值?
Best Regards,
2 个解决方案
#1
8
Try this one:
试试这个:
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"
Edit: Added the plus/minus sign as an optional character in front. To avoid catching the 5 in 3-5 as negative, you could use ((?<=\s)[+-])?
instead of [+-]
编辑:在前面添加加号/减号作为可选字符。为了避免将3-5中的5作为负数,你可以使用((?<= \ s)[+ - ])?而不是[+ - ]
#2
0
Using lambda and slightly better handling of cases like The value is .5. Next sentence
:
使用lambda并稍微更好地处理案例,如值为.5。下一句话:
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());
#1
8
Try this one:
试试这个:
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"
Edit: Added the plus/minus sign as an optional character in front. To avoid catching the 5 in 3-5 as negative, you could use ((?<=\s)[+-])?
instead of [+-]
编辑:在前面添加加号/减号作为可选字符。为了避免将3-5中的5作为负数,你可以使用((?<= \ s)[+ - ])?而不是[+ - ]
#2
0
Using lambda and slightly better handling of cases like The value is .5. Next sentence
:
使用lambda并稍微更好地处理案例,如值为.5。下一句话:
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());