• C++11 正则表达式——实例2


    下面来介绍和regex_match()很像的regex_search()的使用实例,regex_match()要求正则表达式必须与模式串完全匹配,regex_search()只要求存在匹配项就可以。

    #include <regex>

    #include <iostream>

    #include <string>

     

    int main()

    {

      

       const std::tr1::regex pattern("(\\w+day)");

      

       // the source text

       std::string weekend = "Saturday and Sunday";

       std::smatch result;

       bool match = std::regex_search(weekend, result, pattern);

       if(match)

       {

         

          for(size_t i = 1; i < result.size(); ++i)

          {

             std::cout << result[i] << std::endl;

          }

       }

       std::cout<<std::endl;

       return 0;

    }

    运行结果:

    上面这个例子只能返回第一个匹配的项,如果要返回所有匹配的子序列,可以使用下面的方式:

    #include <regex>

    #include <iostream>

    #include <string>

     

    int main()

    {

       // regular expression

       const std::regex pattern("\\w+day");

     

       // the source text

       std::string weekend = "Saturday and Sunday, but some Fridays also.";

     

       const std::sregex_token_iterator end;  //需要注意一下这里

       for (std::sregex_token_iterator i(weekend.begin(),weekend.end(), pattern); i != end ; ++i)

       {

          std::cout << *i << std::endl;

       }

       std::cout<<std::endl;

       return 0;

    }

    运行结果:

    下面的例子将元音字母打头的单词前面的a替换为an:

    #include <regex>

    #include <iostream>

    #include <string>

     

    int main()

    {

       // text to transform

       std::string text = "This is a element and this a unique ID.";

      

       // regular expression with two capture groups

       const std::regex pattern("(\\ba (a|e|i|u|o))+");

      

       // the pattern for the transformation, using the second

       // capture group

       std::string replace = "an $2";

     

       std::string newtext = std::regex_replace(text, pattern, replace);

     

       std::cout << newtext << std::endl;

       std::cout << std::endl;

       return 0;

    }

    运行结果:

    还是来说明一下,这里主要使用了regex_replace(text, pattern, replace),意思是将text的内容按照pattern进行匹配,匹配成功的使用replace串进行替换,并将替换后的结果作为函数值返回。需要注意的是std::string replace = "an $2"; 这里‘$2’表示模式串的第二个子表达式,

    也就是以a,e,i,o,u开头的单词。

     

     

     

    make it simple, make it happen
  • 相关阅读:
    算法:javascript截取字符串
    【转】解决memcached启动失败
    Ubuntu 16.04 安装 Apache, MySQL, PHP7
    phpstorm2016.3+xdebug调试
    (转)微信开发连接SAE数据库
    php图片上传服务器
    大数据整体市场规模达1000亿,金融、政务等行业应用占据七成份额
    “AI智客计划”
    人工智能 :眼纹识别技术大显神通,一眼认出你
    AI 芯片,是金山还是泡沫?
  • 原文地址:https://www.cnblogs.com/zhuyp1015/p/2438232.html
Copyright © 2020-2023  润新知