<code class="language-html hljs "> // test_reg.cpp : 定義控制台應用程序的入口點。 // #include "stdafx.h" #include <regex> #include <string> #include <assert.h> #include <iostream> static std::string kHtmlSnippet = "<p><img data-cke-saved-src="\" src="\"D:\\DOC\\個人軟件\\需求文檔\\安卓助手\\android\\images\\main\\main.png\"" width="\"30%\"" height="\"30%\""></p>" "<ol><li>" "</li><li>ddd中文歌</li><li>" "</li><li>xxx</li><li>" "</li></ol>" "<p><img data-cke-saved-src="\" src="\"D:\\DOC\\個人軟件\\需求文檔\\安卓助手\\android\\images\\main\\main-about.png\"" width="\"30%\"" height="\"30%\""></p>" "<ol><li>" "</li><li>xxxxx</li><li>" "</li></ol>" "<p><img data-cke-saved-src="\" 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; } </iostream></assert.h></string></regex></code>
輸出:
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>