Template to replace "1/3" with "1 / 3.0"

I am looking for a regex pattern that changes "15 + 15/22 - 16 / 33.0" to "15 + 15 / 22.0 - 16 / 33.0" (changing integer division to division by float). My attempt:

        string test = "15 + 15/22 - 16/33.0";
        Regex regex = new Regex(@"(/[0-9]+[^\.])", RegexOptions.None);
        test = regex.Replace(test, "$1.0");

returns a result "15 + 15/22 .0- 16/33.0.0"that has a space in "22. 0" and ends with ".0.0", which I did not expect. Who can do better?

+4
source share
2 answers

Use backlinks.

(?<=\/)(\d+)\b(?!\.)

Demo

string result = Regex.Replace(str, @"(?<=/)(\d+)\b(?!\.)", "$1.0");

Explanation:

  • (?<=\/) A positive lookbehind statement that states that a slash must precede a match.
  • (\d+) Capture one or more digital characters.
  • \b , , .
  • (?!\.) , , .
+5

string test = "15 + 15/22 - 16/33.0";
Regex regex = new Regex(@"(/[0-9]+)([^\.0-9])", RegexOptions.None);
test = regex.Replace(test, "$1.0$2");
+1

All Articles