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
原文地址:https://www.cnblogs.com/zhuyp1015/p/2438232.html