【问题标题】:Regular expression in C++ throwing error "Invalid special open parenthesis."C++ 中的正则表达式抛出错误“无效的特殊左括号”。
【发布时间】:2017-05-22 17:29:04
【问题描述】:

我目前正在处理这样的查询:

a.b.c.d.e~f

我正在尝试提取 a、b、c、d、e 和 f。

我在提取句点分隔值方面取得了一些进展,但我仍然陷入困境,因为我似乎使用 PCRE (?<=~).* 提取最后一个元素(以波浪号“~”开头)的特殊查询,因为它在运行时失败。

我收到了一个非常独特的错误(至少根据谷歌),它是“

terminate called after throwing an instance of 'std::regex_error'
  what():  Invalid special open parenthesis.
Aborted (core dumped)

这是我的代码:

#include <string>
#include <iostream>
#include <regex>
using namespace std;

int main() {  
  const string example = "a.b.c~height";

  regex regex_query_path(R"rgx([^.]+(?=[^~]*~))rgx");

  std::smatch m;
  string test = example;
  while (std::regex_search (test,m,regex_query_path)) {
    cout << "path: " << m[0] << endl;
    test = m.suffix().str();
  }

  regex regex_query_name(R"rgx((?<=~).*)rgx");

  test = example;
  while (std::regex_search (test,m,regex_query_name)) {
    cout << "query: " << m[0] << endl;
    test = m.suffix().str();
  }
  return 0;
}

我在 Ubuntu 16.08 上使用 g++ -std=c++14 和 gcc 版本 6.2.0 编译它。

任何帮助将不胜感激。谢谢!

【问题讨论】:

  • 你弄明白了吗?我也遇到了 std::regex("(?:^|,)(?=[^\"]|(\")?)\"?((?(1)[^\"]*| [^,\"]*))\"?(?=,|$)")

标签: c++ regex pcre


【解决方案1】:

如果你想使用括号,你需要用反斜杠转义它们。

这是一个例子:

std::string regexstring = "\\([a-z]\\):\\([0-9]\\)";

【讨论】:

  • 他不是在尝试匹配括号,而是在做组。
猜你喜欢
  • 2018-04-29
  • 2013-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-04
相关资源
最近更新 更多