c++ 正则匹配
作者:互联网
语法:
std::regex //pattern
std::regex_match //对string用pattern进行匹配, 从头匹配到尾
std::match_results //捕获匹配的内容
代码
#include <iostream>
#include <regex>
int main()
{
using std::string;
using std::cout;
using std::endl;
using std::regex;
using std::regex_match;
using std::match_results;
string s0 = "012-3456-789";
//设置patten, R"()"表示内部是正则字符串, \就表示\, 不需要用\\转义
regex regex_number(R"((\d+)-(\d+)-(\d+))");
//声明match_results, 用于捕获匹配内容
match_results<string::const_iterator> match_results_number;
//进行匹配, 注意regex_match会匹配整个字段, 从头到尾
bool b_match_number = regex_match(s0, match_results_number, regex_number);
//查看匹配结果
if (b_match_number)
{
cout << "match:" << endl;
cout << " 0: " << match_results_number[0] << endl; //整个字串: 012-3456-789
cout << " 1: " << match_results_number[1] << endl; //第一个括号: 123
cout << " 2: " << match_results_number[2] << endl; //第二个括号: 3456
cout << " 3: " << match_results_number[3] << endl; //第三个括号: 789
} else
{
cout << "not match" << endl;
}
//遍历捕获的内容
for(auto iter=match_results_number.begin(); iter!=match_results_number.end(); iter++)
{
//使用iter.str()可以得到对应字符串.
cout << "length=" << iter->length() << ", str=" << iter->str() << endl;
}
//输出:
//length=12, str=012-3456-789
//length=3, str=012
//length=4, str=3456
//length=3, str=789
}
标签:regex,std,匹配,results,c++,number,正则,using,match 来源: https://www.cnblogs.com/gaiqingfeng/p/16323771.html