用于重叠匹配的 C++ 正则表达式

标签 c++ regex greedy

我有一个字符串 'CCCC',我想匹配其中的 'CCC',但要重叠。

我的代码:

...
std::string input_seq = "CCCC";
std::regex re("CCC");
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() << "\t" << "\t" << match.position() << "\t" << "\n";
    next++;
}
...

但是这只会返回

CCC 0 

并跳过我需要的 CCC 1 解决方案。

我读过关于非贪婪的'?'匹配,但我无法让它工作

最佳答案

您的正则表达式可以放入捕获括号中,这些括号可以用正前瞻性包装起来。

要使其在 Mac 上也能正常工作,请通过放置 确保正则表达式在每次匹配时匹配(并因此消耗)一个字符。(或者 - 也匹配换行符 - [\s\S])在先行之后。

然后,您需要修改代码以获取第一个捕获组值,如下所示:

#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;
}

参见 C++ demo

输出:

CCC     0   
CCC     1   

关于用于重叠匹配的 C++ 正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41099513/

相关文章:

c++ - 通过引用传递解引用的指针时了解C++堆/堆栈分配

r - 使用正则表达式提取特定字符串

algorithm - 贪婪与动态

algorithm - 如何证明树上顶点覆盖的贪心算法的正确性?

c++ - 为什么 pthread_create() 返回 0 但线程永远不会启动

c++ - 乘积模随机数

python - 替换位于之间的字符串

regex - gui的Lua模式

c++ - 找到对数组进行排序的最小交换次数

c++ - 重载 '=' 以使 '+' 与矩阵一起使用