如何在正则表达式中将字符串与左大括号 { 匹配C++

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

本文关键字:C++ 匹配 正则表达式 字符串      更新时间:2023-10-16

我有关于用C++编写正则表达式的信息。我有 2 个正则表达式,在 java 中工作正常。但是这些抛出了一个错误,即

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

这些正则表达式如下所示:

 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'

有人可以帮助我如何修复此错误或用C++重写这些正则表达式吗?

请参阅basic_regex参考:

默认情况下,正则表达式模式遵循ECMAScript syntax

ECMAScript 语法参考指出:

人物角色
描述角色
匹配:字符字符,而不在正则表达式中解释其特殊含义。 任何字符都可以转义,但构成上述任何特殊字符序列的字符除外。 需要: ^ $ . * + ? ( ) [ ] { } |

因此,您需要转义{才能使代码正常工作:

std::string s("rn  { rnSome 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;

查看 IDEONE 演示

此外,请注意R"(pattern_here_with_single_escaping_backslashes)"原始字符串文本语法如何简化正则表达式声明。