c++ 11正则表达式的使用方法
版权声明:
本文为博主原创文章,转载请声明原文链接...谢谢。o_0。
更新时间:
2018-03-16 16:55:26
温馨提示:
学无止境,技术类文章有它的时效性,请留意文章更新时间,如发现内容有误请留言指出,防止别人"踩坑",我会及时更新文章
正则方法有regex_match,regex_search,regex_replace
需要的头文件
#include <iostream> #include <string> #include <regex> using namespace std;
regex_match
返回值,匹配成功返回1,失败返回0
注意:这种匹配是整个字符串完全匹配的
另外可以配合 cmatch和smatch类分别存放char*或 string类型字符串的匹配结果,遍历即可获得匹配的值
匹配是不是手机号码
string mobile = "136666666668"; regex re("1\\d{10}"); if (regex_match(mobile, re)) { cout << "是电话号码!\n"; } else { cout << "不是电话号码!\n"; }
分组匹配字符串并且输出匹配的内容
string str = "this is text string!"; regex sre("this(.*?)te(.*?)tring!", regex::icase); smatch sm; regex_match(str, sm, sre); for (unsigned i = 0; i < sm.size(); ++i) { cout << "[" << sm[i] << "] \n"; }
输出结果
regex_search
搜索字符串成功返回1,失败返回0,默认只搜索一次,即第一个匹配
//默认只搜索一次 string seastr = "this her isres1is search! isres2is multi result test isres3is as."; smatch srm;//保存搜索的结果 regex rx("is(.*?)is", regex::icase);//搜索的正则式 regex_search(seastr, srm, rx); cout << srm.str() << endl; cout << srm[1] << endl;
结果
查找所有匹配字符串
第一种方法
string seastr = "thi her isres1is search! isres2is multi result test isres3is as."; smatch srm;//保存搜索的结果 regex rx("is(.*?)is", regex::icase);//搜索的正则式 while (regex_search(seastr, srm, rx)) { cout << "--------------" << endl; for (auto i = 0; i < srm.size(); ++i) { cout << "index " << i << " : [" << srm[i] << "] \n"; } //返回未端,作为新的搜索的开始,一定要设置不然死循环 seastr = srm.suffix().str(); }
结果
第二种使用迭代器搜索所有匹配的字符串
//使用迭代器多次搜索 string seastr = "thi her isres1is search! isres2is multi result test isres3is as."; smatch srm;//保存搜索的结果 regex rx("is(.*?)is", regex::icase);//搜索的正则式 auto ite_begin = sregex_iterator(seastr.begin(), seastr.end(), rx); auto ite_end = sregex_iterator(); for (sregex_iterator i = ite_begin; i != ite_end; ++i) { smatch mat = *i; cout << "--------------" << endl; cout << mat.str() << endl; cout << "index 1:" << mat[1] << endl; }
结果
regex_replace
替换字符串,返回替换后的新字符串,后向引用用 $1,2,3,4
string str = "this is string,that is right;"; regex re("th(.*?) ", regex::icase); string news = regex_replace(str, re, "new[$1]string"); cout << str << endl; cout << news << endl;
结果
sregex_token_iterator
正则分隔字符串
string str = "353this is string,that is right;"; regex sep("\\wh", regex::icase); sregex_token_iterator endite; sregex_token_iterator begite(str.begin(), str.end(), sep, -1); while (begite != endite) { cout << *begite++ << endl; }
结果