Home > front end >  Regex to replace single occurrence of character in C with another character
Regex to replace single occurrence of character in C with another character

Time:11-14

I am trying to replace a single occurrence of a character '1' in a String with a different character.

This same character can occur multiple times in the String which I am not interested in.

For example, in the below string I want to replace the single occurrence of 1 with 2.

 input:-0001011101

 output:-0002011102

I tried the below regex but it is giving be wrong results

  regex b1("(1){1}"); 
  S1=regex_replace( S,
              b1,  "2");

Any help would be greatly appreciated.

CodePudding user response:

Use a negative lookahead in the regexp to match a 1 that isn't followed by another 1:

regex b1("1(?!1)");

CodePudding user response:

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.
  • Related