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++是反人类语言了

posted @   mightofcode  阅读(655)  评论(1编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示