正则表达式匹配失败,特殊左括号无效
Regexp matching fails with invalid special open parenthesis
我正在尝试在 c++11 中使用正则表达式,但我的代码总是抛出Invalid special open parenthesis.
std::regex_error
。一个最小的示例代码,它试图在字符串中查找第一个重复字符:
std::string regexp_string("(?P<a>[a-z])(?P=a)"); // Nothing to be escaped here, right?
std::regex regexp_to_match(regexp_string);
std::string target("abbab");
std::smatch matched_regexp;
std::regex_match(target, matched_regexp, regexp_to_match);
for(const auto& m: matched_regexp)
{
std::cout << m << std::endl;
}
为什么会出现错误以及如何修复此示例?
这里有两个问题:
-
std::regex
风格不支持命名捕获组/反向引用,则需要使用编号的捕获组/反向引用 - 应使用
regex_search
,而不是需要完整字符串匹配的regex_match
。
用
std::string regexp_string(R"(([a-z])1)");
std::regex regexp_to_match(regexp_string);
std::string target("abbab");
std::smatch matched_regexp;
if (std::regex_search(target, matched_regexp, regexp_to_match)) {
std::cout << matched_regexp.str() << std::endl;
}
// => bb
查看C++演示
R"(([a-z])1)"
原始字符串文本定义匹配任何小写 ASCII 字母然后再次匹配同一字母的([a-z])1
正则表达式。
http://en.cppreference.com/w/cpp/regex/ecmascript 说 ECMAScript(std::regex
的默认类型(需要(?=
才能进行积极的展望。
您的正则表达式崩溃的原因是因为 std::regex 不支持命名组。但是,您仍然可以使用可用的内容来查找字符串中的第一个重复字符:
#include <iostream>
#include <regex>
int main()
{
std::string s = "abc def cde";
std::smatch m;
std::regex r("(\w).*?(?=\1)");
if (std::regex_search(s, m, r))
std::cout << m[1] << std::endl;
return 0;
}
指纹
c
相关文章:
- 将 const 转换为 const char* 无效,我该如何解决?使用 gcc7 时失败
- 使用 SQLConfig数据源创建 SQL Server DSN 失败:关键字-值对无效
- 结果失败或多个参数无效
- C ++回测问题:如何检查构造函数在假定失败时是否失败(给定输入的无效参数)
- 获取进程内存信息失败,错误 6 句柄无效
- C++ 调试断言失败,无效的空指针
- 特征 3 断言在求解线性系统时失败 - 据我所知,这是由于特征中的无效索引
- 正则表达式匹配失败,特殊左括号无效
- 类模板的成员函数有条件无效(隐式实例化有效;显式实例化失败)
- C++代码编译失败,错误"长类型名称"无效
- 释放内存失败:free():下一个大小无效(快速):
- 尝试使用 uint*& 作为常量单元*&失败:从类型"uint8_t"的表达式初始化类型"const uint8_t*&"的引用无效
- 成员函数中的decltype(auto)忽略无效的正文,declttype(expr)失败
- 尝试在 QLabel 上绘画失败(无法在没有对象的情况下调用成员函数"虚拟无效 QLabel::p aintEvent(QPaintEvent*)")
- 模板化的出列无效指针:删除类时失败
- 在 cin 失败时捕获无效输入
- 在 Windows 中将原始数据写入磁盘失败,错误代码为 83(参数无效)
- 调试断言失败:无效的空指针
- 最终链接失败:包含 windows.h 时参数无效
- 你好世界在 GCC 5.3.0 上失败 /bin/ld:无效选项 -- 'p'