正则表达式匹配失败,并带有无效的特殊开括号 [英] Regexp matching fails with invalid special open parenthesis
本文介绍了正则表达式匹配失败,并带有无效的特殊开括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在c ++ 11中使用正则表达式,但是我的代码总是抛出 std :: regex_error
为无效的特殊开放括号.
.一个最小的示例代码,尝试查找字符串中的第一个重复字符:
I am trying to use regexps in c++11, but my code always throws an std::regex_error
of Invalid special open parenthesis.
. A minimal example code which tries to find the first duplicate character in a string:
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;
}
为什么会出现错误以及如何解决此示例?
Why do I get an error and how do I fix this example?
推荐答案
这里有2个问题:
-
std :: regex
版本不支持命名捕获组/反向引用,您需要使用编号为 的捕获组/反向引用 - 您应该使用
regex_search
而不是regex_match
表示
std::regex
flavors do not support named capturing groups / backreferences, you need to use numbered capturing groups / backreferences- You should use
regex_search
rather thanregex_match
that requires a full string 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(([[az])\ 1)"
原始字符串文字定义了与任何小写ASCII字母和然后再次匹配相同的字母.
The R"(([a-z])\1)"
raw string literal defines the ([a-z])\1
regex that matches any lowercase ASCII letter and then matches the same letter again.
这篇关于正则表达式匹配失败,并带有无效的特殊开括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文