我有一个字符串 '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/