c++regexcharacter-class

C++ regex_replace to clean concatenated decimal numbers


As part of cleaning up an SVG path data string for display, I want to add spaces between concatenated fractional numbers.

An example would be "0.1.20" should become "0.1 .20" - basically add a space before the second decimal point when you have 2 decimal points separated only by one or more decimal numbers (i.e "2.0" should not become "2 .0")

I tried the following:

#include <iostream>
#include <regex>
#include <string>

void splitString(std::string& pathString) {

  // ... some other clean-up, which works ...

  std::regex re3("(\\.[:digit:]+)(\\.)");$
  pathString = std::regex_replace(pathString, re3, "$1 $2");$

  std::cout << pathString << std::endl;$
}

But when I pass in a string with concatenated decimals like

M 46 -38.9 q 3.7.15 7.65.45 1.2.1 2.35.25 2.75.3 5.05.85 3.85.9 6.5 2.4

it is unchanged on the cout logging line. I'm using similar regexes for cleaning up other elements of the string and they all work correctly, so I'm assuming it's something directly related to the regex itself.


Solution

  • Tried a few more things, and found one that worked.

    Adding a character class around [:digit:] solved the problem.

    std::regex re3("(\\.[[:digit:]]+)(\\.)");
    

    [:digit:] is apparently a class range, which must be wrapped in a character class to be parsed as an atom.