regex使用三个函数简介
(学习参考所用,如有侵权,请及时告知)
链接: [https://blog.csdn.net/qq_34802416/article/details/79307102]
转载:` http://www.cnblogs.com/hucn/archive/2011/05/09/2041490.html
regex_match的含义
// boost::regex_search
template <class BidirectionalIterator, class Allocator, class charT, class traits>
bool regex_search(BidirectionalIterator first, BidirectionalIterator last,
match_results<BidirectionalIterator, Allocator>& m,
const basic_regex<charT, traits>& e,
match_flag_type flags = match_default);
函数概要
判断在[first,last)内是否存在某个子序列匹配正则表达式e, 参数flags用来控制表达式如何匹配字符序列。 如果存在这样的序列则返回true,否则返回false。
参数介绍
重载的函数很类似,这里我们只分析这份
first,last是指向我们要处理的串的首尾迭代器
m是匹配结果,是我们下面说的重点
e是正则表达式
flags是匹配规则
match_results结构的主要成员/方法:
bool empty() const : match_result是否为空,正常应为0(regex_search返回真时),regex_search返回假时match_results结构不确定
size_t size() const : 返回正则表达式中的元组数+1,元组即正则表达式的中的()
const_reference operator[](int n) const : 返回一个sub_match引用,当n=0时返回[first,last)的匹配结果,当0<n<=size时,返回对应元组的匹配结果,
当n>size时返回一个matched值为假的sub_match结构,元组按照左边括号的顺序和sub_match相对应,从1开始。
如regex:(([a-z]+).([0-9]+))+ m[1]:(([a-z]+).([0-9]+)) m[2]:([a-z]+) m[3]:([0-9]+)
sub_match结构的主要成员/方法:
bool matched: 是否匹配
什么是sub_match:
typedef sub_match<const char*> csub_match;
typedef sub_match<const wchar_t*> wcsub_match;
typedef sub_matchstd::string::const_iterator ssub_match;
typedef sub_matchstd::wstring::const_iterator wssub_match;
例子
#include <string>
#include <iostream>
#include <boost\regex.hpp>
void main()
{
std::string str = "192.168.1.1";
boost::regex expression("([0-9]+).([0-9]+).([0-9]+)");
boost::smatch what;
if ( boost::regex_search(str, what, expression) )
{
std::cout << what.size() << std::endl;
for (size_t i = 0; i < what.size(); ++i)
{
if (what[i].matched)
std::cout << what[i] << std::endl;
}
}
}// Output:// 4// 192.168.1// 192// 168// 1