Wednesday, March 31, 2010

Regular Expression to replace number with new value based on orig

Today, I meet a problem, I need replace a lot of numbers in a file with a new value which is based on original value, like the original value is 50, I need use 50*0.8 to replace it.  Regular expression is the best choice, which is a Swiss knife for software engineer. But I am shamed to say that I am not familiar with the regular expression. But we have powerful Stackoverflow. I asked a question in this site, Jens A gave me a pretty answer about it soon.
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();});

No comments:

Post a Comment