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

  • 相关阅读:
    Goahead 3.1.0 发布,嵌入式 Web 服务器
    jdao 1.0.2 发布,轻量级的orm工具包
    pythonbitstring 3.1.0 发布
    JavaScript 搜索引擎 lunr.js
    Difeye 1.1.4 版本发布
    Chronon 3.5 发布,支持 Java 7
    性能扩展的那些事儿:一味增加硬件并不能解决响应时间问题
    Eclipse SDK 4.2.2/Equinox 3.8.2 发布
    Linux Kernel 3.8.1 发布
    Armadillo C++ Library 3.800 发布
  • 原文地址:https://www.cnblogs.com/mightofcode/p/2763156.html
Copyright © 2020-2023  润新知