使用正则表达式查找第一个匹配C++索引

Find index of first match using C++ regex

本文关键字:C++ 索引 第一个 正则表达式 查找      更新时间:2023-10-16

我正在尝试使用正则表达式在C++中编写一个拆分函数。到目前为止,我已经想出了这个;

vector<string> split(string s, regex r)
{
    vector<string> splits;
    while (regex_search(s, r)) 
    {
        int split_on = // index of regex match
        splits.push_back(s.substr(0, split_on));
        s = s.substr(split_on + 1);
    }
    splits.push_back(s);
    return splits;
}

我想知道的是如何填写注释行。

您只需要更多一点,但请参阅下面代码中的注释。男人的技巧是使用匹配对象,这里std::smatch因为你在std::string上匹配,记住你匹配的位置(不仅仅是你做了):

vector<string> split(string s, regex r)
{
  vector<string> splits;
  smatch m; // <-- need a match object
  while (regex_search(s, m, r))  // <-- use it here to get the match
  {
    int split_on = m.position(); // <-- use the match position
    splits.push_back(s.substr(0, split_on));
    s = s.substr(split_on + m.length()); // <-- also, skip the whole match
  }
  if(!s.empty()) {
    splits.push_back(s); // and there may be one last token at the end
  }
  return splits;
}

这可以像这样使用:

auto v = split("foo1bar2baz345qux", std::regex("[0-9]+"));

并会给你"foo", "bar", "baz", "qux".

std::smatchstd::match_results的专业化,此处有参考文档。