#include <iostream>
#include <string>
#include <regex>
using namespace std;
/*
标题:VS2019-std::regex功能测试
最后更新日期:2020-8-28
作者: kagula
环境:VS2019 Community version 16.7.1
注意下面两个方法的区别:
regex_match匹配整个源, regex_search匹配源的一部份。
待改进的地方:
[1]下次有机会, 改成VS单元测试形式.
备注:
[1]建立正则表达式后, 在下面网站(PCRE-PHP)测试通过后, 再移植到C++中.
https://regex101.com/
注意/符号在网站中需要转义, 但是在C++中不需要转义.
*/
int main(int argc, char* argv[])
{
try
{
cout << endl << "示例:匹配整个源,Expression中只有一个capture" << endl;
std::string hello("<img src=\"http://localhost:8080/a.jpg\">");
//<(?:img|IMG)[\s\S]* src="{0,2}(\S+[^"/ ])"{0,2}[\s\S]*/{0,1}>
std::regex rex("<(?:img|IMG)[\\s\\S]*src=\"{0,2}(\\S+[^\"\/ ])\"{0,2}[\\s\\S]*\\/{0,1}>");
std::smatch what;//如果std::string类型替换为boost::smatch
if (std::regex_match(hello, what, rex))
{
cout << what[0] << endl; // whole match
cout << what[1] << endl; // capture
}
/*
打印结果:
http://localhost:8080/a.jpg
*/
}
catch (std::regex_error& e)
{
cout << e.what() << endl;
}
try
{
cout << endl << "示例:匹配整个源,Expression中有多个capture" << endl;
string hello("/webccDemo/user/getInfo.do");
regex rex("/webccDemo/user/(\\w+).do");
smatch what;
if (std::regex_match(hello, what, rex))
{
cout << what[0] << endl; // whole match
cout << what[1] << endl; // first capture
}
/*
打印结果:
/webccDemo/user/getInfo.do
getInfo
*/
}
catch (std::regex_error& e)
{
cout << e.what() << endl;
}
try{
cout << endl << "示例:Expression对源进行多次匹配" << endl;
string src = "<img src=\"http://localhost:8080/a.jpg\"/>ThisIsATest<IMG src=\"http://localhost:8080/b.jpg\"/>";
//<(IMG|img)\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>
//放到std c++的时候, 去掉了?<imgUrl>给group命名的语法, 因为std c++会报告语法出错, 但是boost库支持group命名语法.
string srcExp = "<(IMG|img)\\b[^<>]*?\\bsrc[\\s\\t\\r\\n]*=[\\s\\t\\r\\n]*[\"\"']?[\\s\\t\\r\\n]*([^\\s\\t\\r\\n\"\"'<>]*)[^<>]*?/?[\\s\\t\\r\\n]*";
std::regex expression(srcExp.c_str());
string::const_iterator start = src.begin();
string::const_iterator end = src.end();
std::smatch what;
while (std::regex_search(start, end, what, expression))
{
string ws = what[0].str();
cout << ws << endl;
start = what[0].second;
}
/*
打印结果:
<img src="http://localhost:8080/a.jpg"/>
<IMG src="http://localhost:8080/b.jpg"/>
*/
}
catch (std::regex_error& e)
{
cout << e.what() << endl;
}
cin.get();
return 0;
}
VS2019-std::regex功能测试
猜你喜欢
转载自blog.csdn.net/lee353086/article/details/108279821
今日推荐
周排行