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?
Well,
double.Parse("$1")
tries to parse "$1"
constant string
and fails. I suggest using 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)
你使用"(\\d+(\\.\\d+)?)cm"
和“cm”作为捕获,因为你不能执行`double.Parse(“$ 1”)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.