Convert cm to mm using Regex.Replace ()

I want to make the following input <tag>30.234234cm</tag>and get the following output <tag>302.34234mm</tag>. If the value between the tags is the value in centimeters, which can be decimal or integer, and the goal is to convert this value to millimeters.

var input = "<tag>30.234234cm</tag>";
input = Regex.Replace(input, @"(\d+(\.\d+)?)cm", (double.Parse("$1") * 10).ToString() + 
    "mm", RegexOptions.IgnoreCase);

I use an expression (\d+(\.\d+)?)for the first capture group. However, $1it will not work in context double.Parse($1). How can I get the value of a unit, convert it, and replace it in the above example line?

+4
source share
2 answers

Well,

  double.Parse("$1")

tries to parse a "$1"constant stringand 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);

match.Groups[1].Value - (30.234234 )

+5

"(\d+(\.\d+)?)cm" "cm" , - `double.Parse( "$1" )

0

Source: https://habr.com/ru/post/1669176/


All Articles