C++ 正则表达式返回多项匹配结果

#include <regex>  //我选择了std::tr1::regex 主要是vs2010集成
#include <string>
#include <fstream> //文件读取
#include <sstream> //stringstream,方式二,文件辅助读取
 
using namespace std;


匹配一个html(网易.htm,我已打包)文件中的所有图片,然后添加到listbox中。

 

实现方式一:

sregex_token_iterator

CString strFile;GetDlgItem(IDC_EDIT_HTML)->GetWindowText(strFile);//读取html文件名
//一次性读取 网易.htm 到strHtm中
ifstream file(strFile);
string strHtml;
strHtml.assign(istreambuf_iterator<char>(file.rdbuf()),istreambuf_iterator<char>());file.close();
const std::tr1::regex pattern("http://[^\\\"\\>\\<]+?\\.(png|jpg|bmp)");//简单的匹配正则   
const std::tr1::sregex_token_iterator end; 
for (std::tr1::sregex_token_iterator i(strHtml.begin(),strHtml.end(), pattern); i != end;++i)
{             
	//m_clbRegex.AddString((CString)(*i).str().c_str());//两种操作均可   
	m_clbRegex.AddString((CString)i->str().c_str());//m_clbRegex 为listbox的control变量
}


 

 

实现方式二:

regex_search是返回单项匹配结果,所以我们需要循环多次匹配

CString strFile;    
GetDlgItem(IDC_EDIT_HTML)->GetWindowText(strFile);    
ifstream file(strFile);    
string strHtml;    
stringstream ss;    
ss<<file.rdbuf();       
file.close();    
strHtml=ss.str();//读取html文件到字符串    
std::regex_constants::syntax_option_type fl = std::regex_constants::icase;    
const std::tr1::regex pattern("http://[^\\\"\\>\\<]+?\\.(png|jpg|bmp)",fl);     
std::tr1::smatch result;    
std::string::const_iterator itS = strHtml.begin();
std::string::const_iterator itE = strHtml.end();    
while(regex_search(itS,itE, result, pattern))//如果匹配成功
{        
	//m_clbRegex.AddString((CString)result[0].str().c_str());         
	m_clbRegex.AddString((CString)(string(result[0].first,result[0].second)).c_str());        
	itS=result[0].second;//新的位置开始匹配    
}


 

 

执行结果

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值