C# - 修改字符串中的双打
C# - modify doubles in string
我想编辑字符串中具有较大类型变化的部分的双精度值:
“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());
}
正则表达式归功于:
我想编辑字符串中具有较大类型变化的部分的双精度值:
“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());
}
正则表达式归功于: