此正则表达式在C ++中不起作用 [英] This regex doesn't work in c++
本文介绍了此正则表达式在C ++中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
应该匹配 abababab
,因为 ab
连续重复两次以上,但是代码不打印任何输出。
在C ++中使用正则表达式还有其他技巧吗?
It is supposed to match "abababab"
since "ab"
is repeated more than two times consecutively but the code isn't printing any output.
Is there some other trick in using regex in C++.
我尝试过使用其他语言,而且效果很好。
I tried with other languages and it works just fine.
#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;
}
推荐答案
您的问题是您的反斜杠是转义字符串中的 1。您需要通知std :: regex将其视为。您可以通过使用原始字符串R((。+)\1\1 +)或转义斜线来完成此操作,如下所示:
Your problem is your backslashes are escaping the '1''s in your string. You need to inform std::regex to treat them as '\' 's. You can do this by using a raw string R"((.+)\1\1+)", or by escaping the slashes, as shown here:
#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;
}
哪个会产生输出
abababab ab
这篇关于此正则表达式在C ++中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文