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

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

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

最佳答案

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

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 的特化,存在引用文档 here .

关于c++ - 使用 C++ 正则表达式查找第一个匹配项的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27927913/

相关文章:

c++ - 使用两个函数显示小于或等于c++中输入的素数

java - split ("\\W") 和 split ("[^\\w' ]"有什么区别

c# - 正则表达式匹配字符串中的连字符 0 次或 1 次

javascript - RegExp/JavaScript : Split string on multiple characters, 保留分隔符而不使用lookbehind

Java:强制组件填满 GridLayout 中的整行

c++ - 从管道读取随机失败

c++ - 将数组/指针作为模板参数传递

c++ - 什么是编译时多态性,为什么它只适用于函数?

java - java中连续重复字符的替换

swift - 如何在序列的最后一次出现处拆分字符串