正则表达式匹配失败,特殊左括号无效

Regexp matching fails with invalid special open parenthesis

本文关键字:无效 失败 正则表达式      更新时间:2023-10-16

我正在尝试在 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