C++正则表达式的使用
2015-12-25 19:56
435 查看
C++里面使用正则表达式一般有三种:C regex,C ++regex,boost regex
C regex 的速度是最快的
C++ regex 速度一般
boost regex 速度最慢,但是用起来最方便
速度上大约是这么个情况:V(C)=5V(C++)=10(Boost)
[声明:以上速度是个人测试,仅供参考]
下面看用法:
C++版本:
C regex 的速度是最快的
C++ regex 速度一般
boost regex 速度最慢,但是用起来最方便
速度上大约是这么个情况:V(C)=5V(C++)=10(Boost)
[声明:以上速度是个人测试,仅供参考]
下面看用法:
C++版本:
// Regex.cpp : 定义控制台应用程序的入口点。 // #include <regex> #include <iostream> #include <stdio.h> #include <string> using namespace std; //电子邮件匹配 bool is_email_valid(const std::string& email) { const regex pattern("(\\w+)(\\.|_)?(\\w*)@(\\w+)(\\.(\\w+))+"); /**** const std::regex pattern("(\\w+)(\\.|_)?(\\w*)@(\\w+)(\\.(\\w+))+"); std:: match_results<std::string::const_iterator> result; bool valid = std::regex_match(email, result,pattern); //此处result参数可有可无,result是一个字符串数组,用来存储正则表达式里面括号的内容。 if(valid&&(result.length()>0)) { for(int i =0;i<result.length();i++) { cout<<result[i]<<endl; } } return valid; } //IP地址匹配 bool is_IPAddress_valid(const std::string& ipaddress) { const std::regex pattern("(\\d{1,3}).(\\d{1,3}).(\\d{1,3}).(\\d{1,3})"); //三位数的都可以,没有设置1-255 的条件 std:: match_results<std::string::const_iterator> result; bool valid = std::regex_match(ipaddress, result, pattern); if(valid&&(result.length()>0)) { for(int i =0;i<result.length();i++) { cout<<result[i]<<endl; } } return valid; } int main(int argc,char** argv) { cout<<"测试4个电子邮件选项"<<endl; 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; cout<<"测试4个IP地址选项"<<endl; std::string IPAddress1 = "202.20.144.3"; std::string IPAddress2 = "255.02.233.02"; std::string IPAddress3 = "127.256.2.36"; std::string IPAddress4 = "123.-25.56.125"; std::cout << IPAddress1 << " : " << (is_IPAddress_valid(IPAddress1) ? "valid" : "invalid") << std::endl; std::cout << IPAddress2 << " : " << (is_IPAddress_valid(IPAddress2) ? "valid" : "invalid") << std::endl; std::cout << IPAddress3 << " : " << (is_IPAddress_valid(IPAddress3) ? "valid" : "invalid") << std::endl; std::cout << IPAddress4 << " : " << (is_IPAddress_valid(IPAddress4) ? "valid" : "invalid") << std::endl; return 0 ; }
const std::regex pattern("(\\w+)(\\.|_)?(\\w*)@(\\w+)(\\.(\\w+))+");首先注意‘()’表示将正则表达式分成子表达式,每个‘()’之间的内容表示一个子表达式;‘\’是一个转义字符,‘\’表示扔掉第二个‘\’的转义特性,‘\w+’表示匹配一个或多个单词,‘+’表示重复一次或者多次,因此第一个子表达式的意思就是匹配一个或者多个单词;接着看第二个子表达式,‘|’表示选择,出现‘.’或者‘’,后面的‘?’表示该子表示出现一次或者零次,因此第二个子表示表示‘.’或‘’出现不出现都匹配。第三个子表达式表示出现一个单词,‘*’表示任意个字符。