Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;用于重叠匹配的正则表达式_C++_Regex_Greedy - Fatal编程技术网

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

C++ C++;用于重叠匹配的正则表达式,c++,regex,greedy,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::

我有一个字符串'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++;
}
...
并跳过我需要的
ccc1
解决方案


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

您的正则表达式可以放在捕获括号中,可以用正向前瞻包装

要使其在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;
}

谢谢,它解决了。我会尽快把这个问题标记为已解决。这会导致apple clang上出现无限循环。@RichardHodges:这一定与:Mac实现无法有效处理空匹配有关。在前瞻之后添加的
可能会解决以下问题:。如果必须匹配换行符,则应将
替换为
[\s\s]
。确认-这在mac上有效:
“(?=(CCC))。”
您可能需要编辑答案。
#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;
}
CCC     0   
CCC     1