有人可以举例说明pcrecpp“DoMatch”程序吗?

时间:2011-05-25 06:23:18

标签: pcre

有人可以举例说明pcrecpp DoMatch例程吗?基本上我的要求是将所有匹配捕获到一个向量中。我不想使用FullMatch或PartialMatch,因为它们会在传递给它们的参数中记录匹配。

1 个答案:

答案 0 :(得分:1)

我刚才在网上找到了这个例子。我现在似乎无法找到链接。

vector<string> regex_tools::regex_matches(const string& str
                                          , const string& regex
                                          , bool ignorecase
                                          , bool submatches)
{
  vector<string> svec;
  pcrecpp::RE_Options opt(PCRE_DEF_FLAGS);
  opt.set_caseless(ignorecase);
  pcrecpp::RE re(regex, opt);

  int n = re.NumberOfCapturingGroups();
  if (n <=0)
    return svec;

  else if(n > 10){
    fprintf(stderr, "Overflow: There are too many capturing groups\n");
    return svec;
  }
  /* sigh */


  string matches[10];
  const pcrecpp::Arg *args[10];

  int z = 0;
  pcrecpp::Arg arg0 = &matches[z];
  args[z++] = &arg0;

  pcrecpp::Arg arg1 = &matches[z];
  args[z++] = &arg1;

  pcrecpp::Arg arg2 = &matches[z];
  args[z++] = &arg2;

  pcrecpp::Arg arg3 = &matches[z];
  args[z++] = &arg3;

  pcrecpp::Arg arg4 = &matches[z];
  args[z++] = &arg4;

  pcrecpp::Arg arg5 = &matches[z];
  args[z++] = &arg5;

  pcrecpp::Arg arg6 = &matches[z];
  args[z++] = &arg6;

  pcrecpp::Arg arg7 = &matches[z];
  args[z++] = &arg7;

  pcrecpp::Arg arg8 = &matches[z];
  args[z++] = &arg8;

  pcrecpp::Arg arg9 = &matches[z];
  args[z++] = &arg9;

  pcrecpp::StringPiece input(str);

  int consumed;

  do {
    if (re.DoMatch(input, RE::UNANCHORED, &consumed, args, n)) {
      input.remove_prefix(consumed);
      for (int t = 0; t < n; t++){
        svec.push_back(matches[t]);
      }
    }

    else
        break;
  } while (submatches);
  return svec;
}