I want to take the following input <tag>30.234234cm</tag>
and get the following output <tag>302.34234mm</tag>
. Where the value between the tags is a value in centimetres that may be decimal or integer, and the goal is to convert that value to millimetres.
我想采用以下输入
var input = "<tag>30.234234cm</tag>";
input = Regex.Replace(input, @"(\d+(\.\d+)?)cm", (double.Parse("$1") * 10).ToString() +
"mm", RegexOptions.IgnoreCase);
I am using the expression (\d+(\.\d+)?)
for the first capture group. However, $1
will not work in the context of double.Parse($1)
. How can I get the value of the unit, convert it and replace it in the example string provided?
我正在使用表达式(\ d +(\。\ d +)?)作为第一个捕获组。但是,$ 1在double.Parse($ 1)的上下文中不起作用。如何获取单元的值,转换它并在提供的示例字符串中替换它?
2 个解决方案
#1
5
Well,
double.Parse("$1")
tries to parse "$1"
constant string
and fails. I suggest using lambda:
尝试解析“$ 1”常量字符串并失败。我建议使用lambda:
var input = "<tag>30.234234cm</tag>";
input = Regex.Replace(
input,
@"(\d+(\.\d+)?)cm",
match => (double.Parse(match.Groups[1].Value) * 10).ToString() + "mm",
RegexOptions.IgnoreCase);
Here match.Groups[1].Value
is a value of the captured group (30.234234
in the example)
这里match.Groups [1] .Value是捕获组的值(示例中为30.234234)
#2
0
You're using "(\d+(\.\d+)?)cm"
with "cm" as a capture, because of that you can't perform `double.Parse("$1")
你使用“(\ d +(\。\ d +)?)cm”和“cm”作为捕获,因为你不能执行`double.Parse(“$ 1”)
#1
5
Well,
double.Parse("$1")
tries to parse "$1"
constant string
and fails. I suggest using lambda:
尝试解析“$ 1”常量字符串并失败。我建议使用lambda:
var input = "<tag>30.234234cm</tag>";
input = Regex.Replace(
input,
@"(\d+(\.\d+)?)cm",
match => (double.Parse(match.Groups[1].Value) * 10).ToString() + "mm",
RegexOptions.IgnoreCase);
Here match.Groups[1].Value
is a value of the captured group (30.234234
in the example)
这里match.Groups [1] .Value是捕获组的值(示例中为30.234234)
#2
0
You're using "(\d+(\.\d+)?)cm"
with "cm" as a capture, because of that you can't perform `double.Parse("$1")
你使用“(\ d +(\。\ d +)?)cm”和“cm”作为捕获,因为你不能执行`double.Parse(“$ 1”)