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

Mau*_*kye 3 c++ regex split

我正在尝试使用正则表达式在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;
}
Run Code Online (Sandbox Code Playgroud)

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

Win*_*ute 7

您只需要多一点,但请参阅下面代码中的注释.男人的技巧是使用一个匹配的对象,在这里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;
}
Run Code Online (Sandbox Code Playgroud)

这可以这样使用:

auto v = split("foo1bar2baz345qux", std::regex("[0-9]+"));
Run Code Online (Sandbox Code Playgroud)

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

std::smatch是一个专业化std::match_results,这里有参考文献.