使用Google RE2同时匹配多个正则表达式

5
我希望使用Google的RE2库快速匹配许多(500+)正则表达式,以便获得类似于这篇白皮书中的结果。 我想在第13页上使用RE2-m。
从我在网上看到的内容来看,Set接口是正确的选择,但我不确定该如何入手——我没有找到使用集合接口的Google RE2教程。 请问有人能指点我吗?
1个回答

3

今天我为正在开发的项目实现了这个功能,以下是代码片段,供未来读者参考。

使用RE2处理此问题的正确类别是RE2::Set,您可以在此处找到代码。

以下是示例:

std::vector<std::string> kRegexExpressions = {
  R"My name is [\w]+",
  R"His number is [\d]+",
};

RE2::Set regex_set(RE2::DefaultOptions, RE2::UNANCHORED);

for (const auto &exp : kRegexExpressions) {
  int index = regex_set.Add(exp, &err);
  if (index < 0) {
    <report-error>
    return;
  }
}

if (!regex_set.Compile()) {
  <report-error>
  return;
}

std::vector<int> matching_rules;
if (!regex_set_.Match(line, &matching_rules)) {
  <no-match>
  return;
}

for (auto rule_index : matching_rules) {
  std::cout << "MATCH: Rule #" << rule_index << ": " << kRegexExpressions << std::endl;
}

我们一旦找到匹配的结果,可以停止继续匹配吗? - undefined
Match() 似乎调用了 bool ret = prog_->SearchDFA(text, text, Prog::kAnchored, Prog::kManyMatch(参见 re2/re2/set.cc)。看起来在 re2/re2/dfa.cc 的实现中,当你将 NULL 作为输出参数传递时,它支持这种用法。也就是说,你不需要获取实际的匹配结果,只想检查是否存在匹配。我不认为你有办法获取第一个匹配结果。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接