它应该匹配,"abababab"
因为"ab"
连续重复两次以上,但代码没有打印任何输出。在 C++ 中使用正则表达式还有其他技巧吗?
我尝试了其他语言,效果很好。
#include<bits/stdc++.h>
int main(){
std::string s ("xaxababababaxax");
std::smatch m;
std::regex e ("(.+)\1\1+");
while (std::regex_search (s,m,e)) {
for (auto x:m) std::cout << x << " ";
std::cout << std::endl;
s = m.suffix().str();
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
您的问题是您的反斜杠正在转义字符串中的“1”。您需要通知 std::regex 将它们视为 '\' 。您可以通过使用原始字符串 R"((.+)\1\1+)" 或通过转义斜杠来执行此操作,如下所示:
#include <regex>
#include <string>
#include <iostream>
int main(){
std::string s ("xaxababababaxax");
std::smatch m;
std::regex e ("(.+)\\1\\1+");
while (std::regex_search (s,m,e)) {
for (auto x:m) std::cout << x << " ";
std::cout << std::endl;
s = m.suffix().str();
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
产生输出
abababab ab
Run Code Online (Sandbox Code Playgroud)