How to replace consecutive characters with only one using RegEx in C++

1 Answer

0 votes
#include <iostream>
#include <string>
#include <regex>

int main() {
    std::string input = "aaaabbbccdddddd";
    // Matches any character (.) followed by itself one or more times (\\1+)
    std::regex pattern("(.)\\1+"); 
    
    // Replaces with the first captured group
    std::string result = std::regex_replace(input, pattern, "$1"); 

    std::cout << "Original: " << input << std::endl;
    std::cout << "Modified: " << result << std::endl;
}



/*
run:

Original: aaaabbbccdddddd
Modified: abcd

*/

 



answered Jun 6, 2025 by avibootz
...