//#include <boost/regex.hpp>
//using namespace boost;
#include <regex>
#include <string>
#include <iostream>
using namespace std;
void regex_test()
{
string pattern("[^c]ei");
pattern = "[[:alpha:]]*" + pattern + "[[:alpha:]]*";
//pattern = "[[:alpha:]]*"; //匹配零个多多个任意字母
regex r(pattern,regex::icase); //regex::icase标志:在匹配过程中忽略大小写。
smatch results; //用来保存搜索结果
string test_str("receipt frEind theif receive");
//寻找第一个与正则表达式匹配的子序列,并将结果放入到smatch容器中。
//如果输入序列中一个子串与表达式匹配,则regex_search函数返回true。
if (regex_search(test_str, results, r)){
cout << results.str(0) << endl;
cout << "before "<<results.prefix().str() << endl; //m.prefix()函数,表示当前匹配之前的序列
cout << "after "<<results.suffix().str() << endl; //suffix()函数,表示当前匹配之后的部分
}
//如果整个输入序列与表达式匹配,则regex_match函数返回true
if (regex_match(test_str, r)){
cout << "ture" << endl;
}
else{
cout << "false" << endl;
}
//regex迭代器:sregex_iterator(b,e,r),来获取所有匹配。
for (sregex_iterator ite(test_str.begin(), test_str.end(), r), end_ite; ite != end_ite; ++ite){
cout << ite->str()<< endl;
}
//子表达式:模式通常包含一个或多个子表达式,通常用括号表示子表达式
//子表达式常见用途是验证必须匹配特定格式的数据(如电话号码,IP地址等)
pattern = "(\\()?(\\d{3})(\\))?([-. ])?(\\d{7})";
regex re_tell(pattern);
string tell_str("123-1234567");
if (regex_match(tell_str, re_tell)){
cout << "phone matched" << endl;
}
else{
cout << "phone did not match" << endl;
}
//string fmt("$2.$5.");
//cout << regex_replace(tell_str, re_tell, fmt) << endl;
//ip
}
c++11:正则表达式(re)
最新推荐文章于 2025-06-09 20:55:20 发布