If you used boost::regex
, Boost regex library, you could simply use a lookaround-based solution like
(?<!1)1(?!1)
And then replace with 2
.
With std::regex
, you cannot use lookbehinds, but you can use a regex that captures either start of string or any one char other than your char, then matches your char, and then makes sure your char does not occur immediately on the right.
Then, you may replace with $01
backreference to Group 1 (the 0
is necessary since the $12
replacement pattern would be parsed as Group 12, an empty string here since there is no Group 12 in the match structure):
regex reg("([^1]|^)1(?!1)");
S1=std::regex_replace(S, regex, "$012");
See the C++ demo online:
#include <iostream>
#include <regex>
int main() {
std::string S = "-0001011101";
std::regex reg("([^1]|^)1(?!1)");
std::cout << std::regex_replace(S, reg, "$012") << std::endl;
return 0;
}
// => -0002011102
Details:
([^1]|^)
- Capturing group 1: any char other than 1
([^...]
is a negated character class) or start of string (^
is a start of string anchor)
1
- a 1
char
(?!1)
- a negative lookahead that fails the match if there is a 1
char immediately to the right of the current location.