加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

使用C正则表达式查找第一场比赛的索引

发布时间:2020-12-16 09:55:59 所属栏目:百科 来源:网络整理
导读:我正在尝试使用正则表达式在C中编写分割函数.到目前为止,我已经想出了这个; vectorstring split(string s,regex r){ vectorstring splits; while (regex_search(s,r)) { int split_on = // index of regex match splits.push_back(s.substr(0,split_on)); s
我正在尝试使用正则表达式在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;
}

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

解决方法

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读