Hi all
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?
Best Regards,
Hi all
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?
Best Regards,
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 [+-]
Using lambda and slightly better handling of cases like 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());