gpt4 book ai didi

c++ - 如何在 C++ 正则表达式中匹配带有左大括号 { 的字符串

转载 作者:行者123 更新时间:2023-11-30 03:44:26 25 4
gpt4 key购买 nike

我想用 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 reference :

By default, regex patterns follow the ECMAScript syntax.

ECMAScript syntax reference状态:

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: ^ $ \ . * + ? ( ) [ ] { } |

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

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 demo

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

关于c++ - 如何在 C++ 正则表达式中匹配带有左大括号 { 的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35466091/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com