博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
正则匹配
阅读量:6688 次
发布时间:2019-06-25

本文共 2245 字,大约阅读时间需要 7 分钟。

#include <iostream>

#include <string>
#include <regex>
using namespace std;

int main()

{
//regex_match匹配整个字符串
//reg1匹配大小写字母,不能匹配空格
regex reg1("\\w+day");
smatch r1;
string s1 = "Sat123urdayday";
cout << boolalpha << regex_match(s1,r1,reg1) << endl; //true
cout << "s1匹配结果:" << r1.str() << endl;

//regex_match只返回第一个匹配结果

//string s2 = "saturday and sunday"; //false
string s2 = "saturaday ndsunday"; //true
smatch r2;
cout << boolalpha << regex_match(s2, r2, reg1) << endl; //false
cout << "s2匹配结果:" << r2.str() << " 1234654" << endl; //结果为空

smatch rr1;
smatch rr2;
cout << boolalpha << regex_search(s1, rr1, reg1) << endl;
cout << "s1匹配结果:" << rr1.str() << endl;
cout << boolalpha << regex_search(s2, rr2, reg1) << endl;
cout << "s2匹配结果:" << rr2.str() << " asdasd5" << endl;
cout << endl;

//使用iterator返回多个匹配结果
//结果要用->
cout << "iterator结果:" << endl;
sregex_iterator it(s2.begin(), s2.end(), reg1);
sregex_iterator end;
for(; it != end; ++it)
{
cout << it->str() << endl;
//cout << *it << endl; 错误
}

cout << "token_iterator结果:" << endl;

sregex_token_iterator tit(s2.begin(), s2.end(), reg1);
sregex_token_iterator tend;
for(; tit != tend; ++tit)
{
cout << tit->str() << endl;
cout << *tit << endl;
}

//子表达式匹配

regex reg2("(\\d{1,3}):(\\d{1,3}):(\\d{1,3}):(\\d{1,3})");
string ip = "0:11:222:333";
smatch m;
regex_match(ip, m, reg2);
cout << "输出:str()" << endl;
cout << m.str() << endl;
cout << m.str(1) << endl;
cout << m.str(2) << endl;
cout << m.str(3) << endl;
cout << m.str(4) << endl;

cout << "输出:[i]" << endl;

cout << m[0] << endl;
cout << m[1] << endl;
cout << m[2] << endl;
cout << m[3] << endl;
cout << m[4] << endl;

//输出结果同上

//regex_search(ip, m, str2);
cout << endl;
string ip2 = "0:11:222:333 4:55:66:7";
sregex_iterator ip_it(ip2.begin(), ip2.end(), reg2);
sregex_iterator ip_end;
for(; ip_it != ip_end; ++ip_it)
{
cout << ip_it->str() << endl;
cout << ip_it->str(1) << endl;
cout << ip_it->str(2) << endl;
cout << ip_it->str(3) << endl;
cout << ip_it->str(4) << endl;
}

regex regx("\\d{18}");

regex regx1("\\d{17}+[X]");
smatch sma;
string str = "41282519980203733X";
cout << boolalpha << regex_match(str,sma,regx1) << endl; //true
cout << "s1匹配结果:" << sma.str() << endl;

return 0;

}

转载于:https://www.cnblogs.com/huhusw/p/10884326.html

你可能感兴趣的文章
基于Windows 2016搭建iTop2.6 ticket系统
查看>>
[新手-数据分析师]pandas的学习笔记
查看>>
powershell 批量获取windows 硬盘使用量
查看>>
unicode编码UTF-8和locale概念
查看>>
ubuntu下使用本地软件包APT
查看>>
Javascript模块化编程(三):require.js的用法
查看>>
TCP序列号和确认号详解
查看>>
iptables服务开启的状态测试不会出现unknown key的错误
查看>>
centos安装apache的apr
查看>>
我的友情链接
查看>>
修改openssh配置
查看>>
【按住你的心】——Android开发初识Android项目构成
查看>>
子网划分
查看>>
kindeditor(富文本编辑器)的使用
查看>>
405 Not Allowed nginx/0.7.67
查看>>
SteamOS:Linux 游戏的现状
查看>>
Linux用户切换 su 与 su -
查看>>
RHEL 7.1操作系统安装过程说明
查看>>
基于Python的性能自动化测试框架设计思路和实现
查看>>
Qt之实现360安全卫士主界面(三)
查看>>