使用boost::regex_search进行字符串提取

  使用正则表达式来能够处理很复杂的字符串,这里只分析以下如何使用boost::regex_search进行字符串提取。
  主角登场:

  

    
// boost::regex_search
1 template < class BidirectionalIterator, class Allocator, class charT, class traits >
2 bool regex_search(BidirectionalIterator first, BidirectionalIterator last,
3 match_results < BidirectionalIterator, Allocator >& m,
4 const basic_regex < charT, traits >& e,
5 match_flag_type flags = match_default);

函数概要

  判断在[first,last)内是否存在某个子序列匹配正则表达式e, 参数flags用来控制表达式如何匹配字符序列。 如果存在这样的序列则返回true,否则返回false。

参数介绍

重载的函数很类似,这里我们只分析这份

  1. first,last是指向我们要处理的串的首尾迭代器
  2. m是匹配结果,是我们下面说的重点
  3. e是正则表达式
  4. 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_match
< std:: string ::const_iterator > ssub_match;
typedef sub_match
< std::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

   

参考资料

转载请注明出处:
  

转载于:https://www.cnblogs.com/hucn/archive/2011/05/09/regex_search.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值