Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression to replace the numbers in a file

Tags:

c#

regex

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,

like image 666
Yongwei Xing Avatar asked Mar 31 '10 06:03

Yongwei Xing


Video Answer


1 Answers

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 [+-]

like image 189
Jens Avatar answered Oct 19 '22 21:10

Jens