C++11 正则表达式——实例1

来源:互联网 发布:dijkstra算法优先队列 编辑:程序博客网 时间:2024/04/30 14:24

 该实例通过一个函数is_email_valid 来检查一个email地址是否是一个正确的格式。如果格式正确则返回true。

#include <regex>

#include <iostream>

#include <string>

 

bool is_email_valid(const std::string& email)

{

  

   const std::regex pattern("(\\w+)(\\.|_)?(\\w*)@(\\w+)(\\.(\\w+))+");

 

   return std::regex_match(email, pattern);

}

 

int main()

{

   std::string email1 = "marius.bancila@domain.com";

   std::string email2 = "mariusbancila@domain.com";

   std::string email3 = "marius_b@domain.co.uk";

   std::string email4 = "marius@domain";

 

   std::cout << email1 << " : " << (is_email_valid(email1) ?

      "valid" : "invalid") << std::endl;

   std::cout << email2 << " : " << (is_email_valid(email2) ?

      "valid" : "invalid") << std::endl;

   std::cout << email3 << " : " << (is_email_valid(email3) ?

     "valid" : "invalid") << std::endl;

   std::cout << email4 << " : " << (is_email_valid(email4) ?

     "valid" : "invalid") << std::endl;

 

   return 0;

}

运行结果

     这里对is_email_valid()函数中的正则表达式做一个简短的说明,如果对于正则表示不是很清楚的同学就能很容易理解了。
     const std::regex pattern("(\\w+)(\\.|_)?(\\w*)@(\\w+)(\\.(\\w+))+"); 首先注意‘()’表示将正则表达式分成子表达式,每个‘()’之间的内容表示一个子表达式;‘\’是一个转义字符,‘\\’表示扔掉第二个‘\’的转义特性,‘\w+’表示匹配一个或多个单词,‘+’表示重复一次或者多次,因此第一个子表达式的意思就是匹配一个或者多个单词;接着看第二个子表达式,‘|’表示选择,出现‘.’或者‘_’,后面的‘?’表示该子表示出现一次或者零次,因此第二个子表示表示‘.’或‘_’出现不出现都匹配。第三个子表达式表示出现一个单词,‘*’表示任意个字符。后面的子表示根据已经介绍的内容,已经可以容易理解,就不再赘述。通过对正则表达式匹配模式串的分析,可以容易理解运行结果。

 

下面一个例子通过正则表达式识别和打印IP地址的各个部分:

#include <regex>

#include <iostream>

#include <string>

 

void show_ip_parts(const std::string& ip)

{

   // regular expression with 4 capture groups defined with

   // parenthesis (...)

   const std::regex pattern("(\\d{1,3}):(\\d{1,3}):(\\d{1,3}):(\\d{1,3})");

   // object that will contain the sequence of sub-matches

   std:: match_results<std::string::const_iterator> result;

   // match the IP address with the regular expression

   bool valid = std:: regex_match(ip, result, pattern);

   std::cout << ip << " \t: " << (valid ? "valid" : "invalid")

             << std::endl;

   // if the IP address matched the regex, then print the parts

   if(valid)

   {

      std::cout << "b1: " << result[1] << std::endl;

      std::cout << "b2: " << result[2] << std::endl;

      std::cout << "b3: " << result[3] << std::endl;

      std::cout << "b4: " << result[4] << std::endl;

   }

}

 

int main()

{

   show_ip_parts("1:22:33:444");

   show_ip_parts("1:22:33:4444");

   show_ip_parts("100:200");

 

   return 0;

}

运行结果:

是对正则表达式的模式串做一个说明:首先还是通过‘()’将这个串分成几个子表达式,其中\d表示匹配一个数字,{,}表示数字的个数,例如{1,3}可以理解为匹配一个小于1000的数字(1-3位数都符合匹配要求)。

程序中还使用了match_results类,用来保存匹配的每一个子序列。调用regex_match(ip,result,pattern),表示将ip中与模式串pattern匹配的结果放在result中。

result最后可以通过下标来访问各个匹配的子表达式。

 

http://www.cnblogs.com/zhuyp1015/archive/2012/04/08/2438215.html

原创粉丝点击