如何在正则表达式中将字符串与左大括号 { 匹配C++
How to match a string with an opening brace { in C++ regex
我有关于用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)"
原始字符串文本语法如何简化正则表达式声明。
相关文章:
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 基于ELO的团队匹配算法
- 没有用于初始化C++中的变量模板的匹配构造函数
- 调用'begin(int [n])'没有匹配函数
- 将模板与类模板扣除占位符参数匹配
- 功能样式转换从 'int' 到 'ItemType' 的匹配转换
- 'max'匹配'std::function<const int &(const int &, const int &)>'无过载
- C++LinkedList问题.数据类型之间存在冲突?没有匹配的构造函数
- Qt SQLite没有查询或参数计数不匹配
- 模板参数推导失败,函数参数/参数不匹配
- 错误 没有与参数列表匹配的重载函数"getline"实例
- 在使用累加时,C++中的运算符+不匹配
- 错误:调用'getline'没有匹配函数
- C++ 与操作员不匹配<<
- 我怎样才能将所有子目录与 cmake 自动匹配
- C++:编译时检查匹配的函数调用对?
- 匹配函数指针作为模板参数?
- 矩形类中没有匹配函数
- 在 Arduino 上使用 sscanf 会导致与 const char * 不匹配,并且返回值始终相同,尽管输入值不同
- std::vector 没有重载函数的实例与参数列表匹配