How to match a string with an opening brace { in C++ regex

喜欢而已 提交于 2021-02-05 08:00:49

问题


I have about writing regexes in C++. I have 2 regexes which work fine in java. But these throws an error namely

 one of * + was not preceded by a valid regular expression C++

These regexes are as follows:

 regex r1("^[\s]*{[\s]*\n"); //Space followed by '{' then followed by spaces and '\n'
 regex r2("^[\s]*{[\s]*\/\/.*\n") // Space followed by '{' then by  '//' and '\n'

Can someone help me how to fix this error or re-write these regex in C++?


回答1:


See basic_regex reference:

By default, regex patterns follow the ECMAScript syntax.

ECMAScript syntax reference states:

characters: \character
description: character
matches: the character character as it is, without interpreting its special meaning within a regex expression. Any character can be escaped except those which form any of the special character sequences above. Needed for: ^ $ \ . * + ? ( ) [ ] { } |

So, you need to escape { to get the code working:

std::string s("\r\n  { \r\nSome text here");
regex r1(R"(^\s*\{\s*\n)");
regex r2(R"(^\s*\{\s*//.*\n)");
std::string newtext = std::regex_replace( s, r1, "" );
std::cout << newtext << std::endl;

See IDEONE demo

Also, note how the R"(pattern_here_with_single_escaping_backslashes)" raw string literal syntax simplifies a regex declaration.



来源:https://stackoverflow.com/questions/35466091/how-to-match-a-string-with-an-opening-brace-in-c-regex

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!