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

6

我正在尝试使用正则表达式在C++中编写split函数。目前我已经想出了以下代码:

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;
}

我想知道如何填写注释行。
1个回答

9
你需要的不仅仅是这些,但请查看下面代码中的注释。关键之处在于使用匹配对象,此处为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的一种特化,有相关的参考文档在此处


谢谢,这个完美地运行了。我还在学习C++,这真的很有帮助。 - Maurdekye

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