【问题标题】:Find index of first match using C++ regex使用 C++ 正则表达式查找第一个匹配项的索引
【发布时间】:2015-03-11 17:59:24
【问题描述】:

我正在尝试使用正则表达式在 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;
}

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

【问题讨论】:

    标签: c++ regex split


    【解决方案1】:

    您只需要多一点,但请参阅下面代码中的 cmets。技巧是使用匹配对象,这里是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 的特化,其参考文档存在here

    【讨论】:

    • 谢谢,效果很好。我还在学习 C++,这真的很有帮助。
    猜你喜欢
    • 2013-12-01
    • 1970-01-01
    • 2020-12-03
    • 1970-01-01
    • 1970-01-01
    • 2015-06-01
    • 1970-01-01
    • 2011-03-31
    • 1970-01-01
    相关资源
    最近更新 更多