C++11 正則表達式——實例1


 

 該實例通過一個函數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最后可以通過下標來訪問各個匹配的子表達式。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM