我有一个字符串'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++;
}
...
Run Code Online (Sandbox Code Playgroud)
然而,这只会返回
CCC 0
Run Code Online (Sandbox Code Playgroud)
并跳过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;
}
Run Code Online (Sandbox Code Playgroud)
请参阅C++演示
输出:
CCC 0
CCC 1
Run Code Online (Sandbox Code Playgroud)