如何在C ++正则表达式中用大括号{匹配字符串 [英] How to match a string with an opening brace { in C++ regex
问题描述
我有关于用C ++编写正则表达式的知识.我有2个正则表达式,可以在Java中正常工作.但这就是抛出错误
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++
这些正则表达式如下:
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 ++重新编写这些正则表达式吗?
Can someone help me how to fix this error or re-write these regex in C++?
推荐答案
请参见 basic_regex
参考:
默认情况下,正则表达式模式遵循
ECMAScript语法
.
字符:
\
字符
说明:字符
matches (匹配):字符字符本身,而无需在正则表达式中解释其特殊含义.除构成上述任何特殊字符序列的字符外,任何字符都可以转义. 需要:^
$
\
.
*
+
?
(
)
[
]
{
}
|
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;
请参见 IDEONE演示
此外,请注意 R(pattern_here_with_single_escaping_backslashes)"
原始字符串文字语法如何简化正则表达式声明.
Also, note how the R"(pattern_here_with_single_escaping_backslashes)"
raw string literal syntax simplifies a regex declaration.
这篇关于如何在C ++正则表达式中用大括号{匹配字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!