regex_match
regex_replace
regex_search
#include <iostream>
#include <regex>
#include <string>
using namespace std;
//1.regex_match正则匹配
void test_regex_match()
{
//满足:true 不满足:false
regex email("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$");//构建邮箱正则规则
string Email;
while (1)
{
cin >> Email;
if (regex_match(Email, email))
{
cout << "true" << endl;
break;
}
}
//2.正则匹配是完全匹配
string str = "ILoveyou1314";
regex reg("[a-z0-9]+");//IL不匹配
//大小写问题,构造时忽略大小写
regex reg2("[a-z0-9]+", regex_constants::icase);//匹配str
//3.字符串也可以充当正则规则
regex reg3("ILoveyou");//比匹配str
}
//regex_replace正则替换
void test_regex_replace()
{
//原字符串不变
string str = "ILoveyou1314IMissyou520";
regex reg("\\d+");
regex_replace(str, reg, "我喜欢你");//ILoveyou我喜欢你IMissyou我喜欢你
//替换第一次出现的
regex_replace(str, reg,"我喜欢你", regex_constants::format_first_only);//ILoveyou我喜欢你IMissyou520
//不拷贝原字符串
regex_replace(str, reg, "我喜欢你", regex_constants::format_no_copy);//我喜欢你我喜欢你
//默认方式
regex_replace(str, reg, "我喜欢你", regex_constants::format_default);//ILoveyou我喜欢你IMissyou我喜欢你
}
//regex_search截取捕获字符串
void test_regex_search()
{
//捕获成功返回true
//res.suffix()作为循环条件,继续截取
string str = "ILoveyou1314IMissyou520";
smatch res;
bool flag = regex_search(str, res, regex("\\d+"));
if (flag)
{
for (int i = 0; i < res.size(); i++)
{
cout << res.str() <<endl;//捕获的字符串
}
cout << res.prefix() << endl;//前缀ILoveyou
cout << res.suffix() << endl;//后缀IMissyou520
}
//sregex_iterator持续截取
regex rule("\\d+");
sregex_iterator si(str.begin(), str.end(), rule);
sregex_iterator end;
while (si != end)
{
cout << si->str() << "\t";//1314 520
si++;
}
//sregex_token_iterator拆解字符串
//0:匹配的 -1:不匹配的
sregex_token_iterator begin(str.begin(), str.end(), rule, 0);
sregex_token_iterator end1;
while (begin != end1)
{
cout << begin->str() << "\t";//1314 520
begin++;
}
}
int main()
{
test_regex_match();
test_regex_replace();
test_regex_search();
return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)