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

编程入门 行业动态 更新时间:2024-10-26 03:30:07
本文介绍了如何在C ++正则表达式中用大括号{匹配字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有关于用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语法.

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 ++正则表达式中用大括号{匹配字符串

本文发布于:2023-11-03 12:23:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1555126.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:括号   中用   字符串   如何在   正则表达式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!