标签:
std::regex_replace
std::regex_iterator
Regular Expressions (C++)
// test_reg.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <regex>
#include <string>
#include <assert.h>
#include <iostream>
static std::string kHtmlSnippet = "<p><img src=\"D:\\DOC\\个人软件\\需求文档\\安卓助手\\android\\images\\main\\main.png\" width=\"30%\" height=\"30%\"></p>"
"<ol>"
"<li>ddd中文歌</li>"
"<li>xxx</li>"
"</ol>"
"<p><img src=\"D:\\DOC\\个人软件\\需求文档\\安卓助手\\android\\images\\main\\main-about.png\" width=\"30%\" height=\"30%\"></p>"
"<ol>"
"<li>xxxxx</li>"
"</ol>"
"<p><img src=\"D:\\DOC\\个人软件\\需求文档\\安卓助手\\android\\images\\main\\main-setting.png\" width=\"30%\" height=\"30%\"></p>";
void TestReplace()
{
std::cout << "TestReplace ====" << std::endl;
// 把所有 img src 的绝对路径替换为 images 开始的相对路径.
// 使用分组即可.
std::regex img_regex("(<img [^>]*src=[\"‘]{1})([^\"‘]*)\\\\(images\\\\[^\"‘]*[\"‘]{1}[^>]*>)");
std::smatch color_match;
std::string rep = "$1$3";
std::string tmp = std::regex_replace(kHtmlSnippet,img_regex,rep);
std::cout << tmp << std::endl;
}
void TestSearch()
{
std::cout << "TestSearch ====" << std::endl;
// 查找所有的img完整标签
std::regex img_regex("<img [^>]+>");
// 使用 std::regex_search 查询第一个匹配的字符串.
std::smatch color_match;
std::cout << "regex_search ====" << std::endl;
if(std::regex_search(kHtmlSnippet, color_match, img_regex))
{
std::cout << color_match[0] << ‘\n‘;
}
// 使用类 std::regex_iterator 来进行多次搜索.
std::cout << "sregex_iterator ====" << std::endl;
auto words_begin =
std::sregex_iterator(kHtmlSnippet.begin(), kHtmlSnippet.end(), img_regex);
auto words_end = std::sregex_iterator();
for (std::sregex_iterator i = words_begin; i != words_end; ++i)
{
std::smatch match = *i;
std::string match_str = match.str();
std::cout << match_str << ‘\n‘;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
TestSearch();
TestReplace();
return 0;
}
输出:
TestSearch ====
regex_search ====
<img src="D:\DOC\个人软件\需求文چ
3;\安卓助手\android\images\main\main.png" width="30%" he
ight="30%">
sregex_iterator ====
<img src="D:\DOC\个人软件\需求文چ
3;\安卓助手\android\images\main\main.png" width="30%" he
ight="30%">
<img src="D:\DOC\个人软件\需求文چ
3;\安卓助手\android\images\main\main-about.png" width="3
0%" height="30%">
<img src="D:\DOC\个人软件\需求文چ
3;\安卓助手\android\images\main\main-setting.png" width=
"30%" height="30%">
TestReplace ====
<p><img src="images\main\main.png" width="30%" height="30%"></p><ol><li>ddd中文
歌</li><li>xxx</li></ol><p><img src="images\main\main-about.png" width="30%" hei
ght="30%"></p><ol><li>xxxxx</li></ol><p><img src="images\main\main-setting.png"
width="30%" height="30%"></p>
[C/C++11]_[初级]_[使用正则表达式库regex]
标签:
原文地址:http://blog.csdn.net/infoworld/article/details/50946545