[英]C# - modify doubles in string
我想编辑类型较大变化的字符串中的double值:
“ 1 /(2.342 / x)”
“ x ^ 3.45”
“ 123 * x”
等等。
关于如何只能对其进行修改的任何好的示例? 因为我希望能够将它们更改为新的随机双精度。 例如
“ 1 /(2.342 / x)” --->“ 1 /(23.2 / x)”
“ x ^ 3.45” --->“ x ^ 0.2”
“ 123 * x” ---“ 3.23 * x”
最简单的方法是,使用正则表达式提取浮点值,然后通过float / decimal / double或所需的任何数据类型将它们转换。
修改后,您可以再次使用相同的正则表达式替换字符串。
Regex regex = new Regex(@"[1-9][0-9]*\.?[0-9]*([Ee][+-]?[0-9]+)?");
string testString ="1/(2.342/x) * x^3.45";
MatchCollection collection = regex.Matches(testString);
foreach(Match item in collection)
{
double extract =Convert.ToDouble(item.Value);
//change your decimal here...
testString = testString.Replace(item.Value, extract.ToString());
}
正则表达式贷记到: https : //stackoverflow.com/a/2293793/2084262
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.