tags:

views:

85

answers:

2

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,

+8  A: 

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

Jens
+1 Pretty impressive!
systempuntoout
Gotta love delegates in regex's... Leaves some questions about ".57" or similar, but OP should be able to figure it out... I'm still curious as to whether or not the numbers are the ONLY thing in the file
LorenVS
+1 btw... char limit...
LorenVS
It should also accept an optional `+` or `-` sign.
Turtle
@Turtle: Right you are, adding it.
Jens
thanks it works very well
Yongwei Xing
A: 

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());
Konstantin Spirin