c++ 正则表达式

话说c++11有正则了,在vs2010中有支持,在std里面就有,包含<regex>即可

不过感觉没有c#里用的方便,而且没有@关键词写个正则得麻烦死

声明正则用regex

匹配结果用match_results<T>保存

  typedef match_results<const char *> cmatch;
  typedef match_results<const wchar_t *> wcmatch;
  typedef match_results<string::const_iterator> smatch;
  typedef match_results<wstring::const_iterator> wsmatch;

匹配用regex_match,有多个重载版本,包括返回匹配结果,设置匹配参数等

  regex_match存储了匹配到的字符串

  regex_match[0]返回匹配到的字符串

  regex_match[n]依次匹配每个group

替换用regex_replace,可以使用$n表示子表达式

搜索用regex_search,regex_search不接受string作为参数,很反人类

一些例子

1 search

  string a1="aswha";
  regex r("as(.+)");  
  cmatch cm;
  bool b1=regex_search(a1.c_str(),cm,r);
  cout<<b1<<" "<<cm.size()<<endl;
  cout<<cm[0]<<endl;

  输出1 2 aswha wha

2 replace 

  string a1="a ship a ship";
  regex r("a (\\w*)");
  string rep="an $1";
  cmatch cm;
  string str1=regex_replace(a1,r,rep);
  cout<<str1<<endl;

3 匹配多次

  为什么不能取到每个match然后再取每个子表达式呢,好像只能输出全部的匹配串,没有像c#里面的Matchs的函数吗?难不成要自己撸一个

  string a1="a ship a ship";
  regex r("a (\\w*)");
  string rep="an $1";
  cmatch cm;
  sregex_token_iterator it(a1.begin(),a1.end(),r);
  sregex_token_iterator it2;
  for (;it!=it2;it++)
  {
  cout<<(*it)<<endl;
  }

 

     据说regex对中文支持不好,需要使用宽字符才能正常工作

   regex让我越发觉得c++是反人类语言了

原文链接: https://www.cnblogs.com/mightofcode/archive/2012/11/09/2763156.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    c++ 正则表达式

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/68708

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 下午1:27
下一篇 2023年2月9日 下午1:27

相关推荐