2016-09-24 46 views
2

我想在正则表达式输入字符串替换(为& &和||或子字符串)下面的字符替换他们的修改版本中的字符串替换字符

+ - ! () { } [ ]^" ~ * ? : \ && || 

哪有我写这个请求在构建std :: regex?

例如,如果我有

"(1+1):2" 

我想要的输入:

"\(1\+1\)\:2" 

最后的代码看起来是这样的:

std::string s ("(1+1):2"); 
    std::regex e ("???"); // what should I put here ? 

    std::cout << std::regex_replace (s,e,"\\$2"); // is this correct ? 
+2

'的std :: regex_replace( “(1 + 1):2”,正则表达式( “![ - + \” \\ [\\](){} ^〜 * ?:] | && | \\ | \\ |“),”\\ $ 0“);' – revo

+0

@revo感谢它也可以,但下面的答案有什么区别? – Aminos

+2

区别在于它更短,效率更高,因为它从角色类中受益。 – revo

回答

1

您可以使用std::regex_replace与捕获:

#include <iostream> 
#include <string> 
#include <regex> 

using namespace std; 

int main() { 
    regex regex_a("(\\+|-|!|\\(|\\)|\\{|\\}|\\[|\\]|\\^|\"|~|\\*|\\?|:|\\\\|&&|\\|\\|)"); 
    cout << regex_replace("(1+1):2", regex_a, "\\$0") << endl; 
} 

这将打印

$ ./a.out 
\(1\+1\)\:2 
+0

谢谢!有用 !我如何学习这些东西? – Aminos

+1

@Aminos我基本上学习了Python中的正则表达式,使用它的标准库的文档。这在所有语言中都差不多。你最舒服的语言是什么? –

+0

C++是我使用最多的语言。 – Aminos