【问题标题】:Pattern Matching on every element in the vector向量中每个元素的模式匹配
【发布时间】:2014-09-27 00:53:18
【问题描述】:

我有一个看起来像这样的函数:

bool ExpandWildCard(vector<string>& names, vector<string>& result, string& wildcard) 
{
}

在这里,我想将wildcard 与向量names 中的每个元素进行匹配,如果匹配,则将names 中的元素添加到result 向量中。

当然,如果通配符是 *,我可以添加从 namesresults 的所有内容。另外我现在只是尝试实现* 通配符。

如何在 C++ 中做到这一点?

我想到的一种方法是使用find() 算法,但我不确定我是否会使用它来匹配通配符?

【问题讨论】:

  • 要进行全正则表达式匹配吗?见std::regex
  • 这个问题不是太笼统,很明显是关于如何进行全局匹配。

标签: c++ regex glob


【解决方案1】:

您似乎正在寻找std::copy_ifstd::regex_match 的组合:

bool ExpandWildCard(vector<string>& names, vector<string>& result, string& wildcard) {
  auto oldsize = result.size();
  std::copy_if(std::begin(names), std::end(names),
    std::back_inserter(result),
    [&](string const& name) {
      return std::regex_match(name, make_regex(wildcard));
    }
  );

  return (result.size() > oldsize);
}

make_regex 是将字符串转换为std::regex 所需实现的函数。

【讨论】:

    【解决方案2】:

    another answer 中建议的使用 regex_match 时可能采用的方法。 Elsewhere 你可以找到将 glob 模式转换为正则表达式的代码。

    如果性能不是问题,而您只需要功能,则可以使用 shell 为您匹配模式。您可以创建一个合适的命令,通过popen() 传递命令并读取结果并将它们存储在您的向量中。

    bool ExpandWildCard (const std::vector<std::string>& names,
                         std::vector<std::string>& result,
                         const std::string& wildcard)
    {
        std::ostringstream oss;
        oss << "bash -c 'for word in ";
        for (int i = 0; i < names.size(); ++i) {
            if (names[i].size() > 0) oss << '"' << names[i] << '"' << ' ';
        }
        oss << "; do case \"$word\" in "
            << wildcard << ')' << " echo \"$word\" ;; *) ;; "
            << "esac ; done '";
        FILE *fp = ::popen(oss.str().c_str(), "r");
        if (fp == NULL) return false;
        char *line = 0;
        ssize_t len = 0;
        size_t n = 0;
        while ((len = ::getline(&line, &n, fp)) > 0) {
            if (line[len-1] == '\n') line[len-1] = '\0';
            result.push_back(line);
        }
        ::free(line);
        ::pclose(fp);
        return true;
    }
    

    【讨论】:

      猜你喜欢
      • 2014-08-15
      • 2013-03-09
      • 1970-01-01
      • 1970-01-01
      • 2021-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-18
      相关资源
      最近更新 更多