C ++ regex_replace doesn't do the intended replacement
The following code is for converting the) 9 to the first line into a) * 9. The original line is printed unmodified last line.
std::string ss ("1 + (3+2)9 - 2 ");
std::regex ee ("(\\)\\d)([^ ]");
std::string result;
std::regex_replace (std::back_inserter(result), ss.begin(), ss.end(), ee, ")*$2");
std::cout << result;
This is based on a very similar example: http://www.cplusplus.com/reference/regex/regex_replace/
MS Visual Studio Express 2013.
source to share
I see two problems: firstly, your capture group only needs to include part of the '9'
string, and the second group you want to use for replacement is not $ 2, but $ 1:
std::string ss ("1 + (3+2)9 - 2 ");
static const std::regex ee ("\\)(\\d)");
std::string result;
std::regex_replace (std::back_inserter(result), ss.begin(), ss.end(), ee, ")*$1");
std::cout << result;
Output:
1 + (3 + 2) * 9 - 2
Edit
It looks like you need a more general replacement.
That is, wherever there is a number, followed by an open guy, for example, 1(
or a close wig, followed by a number, for example. )1
... You need an asterisk between the number and the pair.
In C ++, we can do it with regex_replace
, but we need two of them at this writing time. We can link them together:
std::string ss ("1 + 7(3+2)9 - 2");
static const std::regex ee ("\\)(\\d+)");
static const std::regex e2 ("(\\d+)\\(");
std::string result;
std::regex_replace (std::back_inserter(result), ss.begin(), ss.end(), ee, ")*$1");
result = std::regex_replace (result, e2, "$1*(");
std::cout << result;
Output:
1 + 7 * (3 + 2) * 9 - 2
Edit 2
Since you asked in another question how to turn this into one that can also trap whitespace, here is a slight modification to handle possible whitespace between number and paren characters
static const std::regex ee ("\\)\\s*(\\d+)");
static const std::regex e2 ("(\\d+)\\s*\\(");
source to share