C++ regex for overlapping matches

后端 未结 1 1593
半阙折子戏
半阙折子戏 2020-12-06 20:15

I have a string \'CCCC\' and I want to match \'CCC\' in it, with overlap.

My code:

...
std::string input_seq = \"CCCC\";
std::regex re(\"CCC\");
std:         


        
相关标签:
1条回答
  • 2020-12-06 21:07

    Your regex can be put into the capturing parentheses that can be wrapped with a positive lookahead.

    To make it work on Mac, too, make sure the regex matches (and thus consumes) a single char at each match by placing a . (or - to also match line break chars - [\s\S]) after the lookahead.

    Then, you will need to amend the code to get the first capturing group value like this:

    #include <iostream>
    #include <regex>
    #include <string>
    using namespace std;
    
    int main() {
        std::string input_seq = "CCCC";
        std::regex re("(?=(CCC))."); // <-- PATTERN MODIFICATION
        std::sregex_iterator next(input_seq.begin(), input_seq.end(), re);
        std::sregex_iterator end;
        while (next != end) {
            std::smatch match = *next;
            std::cout << match.str(1) << "\t" << "\t" << match.position() << "\t" << "\n"; // <-- SEE HERE
            next++;
        }
        return 0;
    }
    

    See the C++ demo

    Output:

    CCC     0   
    CCC     1   
    
    0 讨论(0)
提交回复
热议问题