boost 正则表达式 regex
环境安装
如果在引用boost regex出现连接错误,但是引用其他的库却没有这个错误,这是因为对于boost来说,是免编译的,但是,正则这个库 是需要单独编译和使用的。简单的办法就是 直接将boost库全部编译,然后 找到正则的lib,编译时候引用进去。
代码example
#include <boost/regex.hpp>
#include <iostream>
#include <string>
#include "TestRe.h"
using namespace::boost;
using namespace::std;
void TestRe::test() {
regex re("(https?://www.ttufo.com/.+/.+/.+)(_\\d+)(.html?)");
//string replace("http://www.ttufo.com/($1)/($2)/($3).htm($5)");
//regex re("http://www.ttufo.com/(.+)/(.+)/(.+)(_.+).htm(l?)");
string target("http://www.ttufo.com/ufo/201705/154053_3.html");
cmatch what;
if (regex_match(target.c_str(), what, re)) {
cout << "match " << what.size() << endl;
for (int i = 0; i < what.size(); i++) {
cout << "what[" << i << "]: " << what[i] << ", first: " << what[i].first << ", second: " << what[i].second << endl;
}
} else {
cout << "not match " << endl;
}
}
void TestRe::test_replace() {
cout << "test replac ----------------" << endl;
string s1 = "(<)|(>)|(&)";
// string s2 = "(?1b)(?2e)(?3...)";
string s2 = "(?1$1)(?2$2)(?3...)";
string target("cout << a&b << endl;");
boost::regex reg( s1 );
string s = boost::regex_replace( target,
reg,
s2,
boost::match_default | boost::format_all);
cout << s << endl;
cmatch what;
target = "cout << a&b << endl;";
if (regex_search(target.c_str(), what, reg)) {
cout << "match " << what.size() << endl;
for (int i = 0; i < what.size(); i++) {
cout << "what[" << i << "]: " << what[i] << ", first: " << what[i].first << ", second: " << what[i].second << endl;
}
} else {
cout << "not match " << endl;
}
cout << "test replac ----------------" << endl;
}
void TestRe::test_replace_1() {
regex reg("(https?://www.ttufo.com/.+/.+/.+)(_\\d+)(.html?)");
string target("https://www.ttufo.com/ufo/201705/154053_3.html");
string replace("http://www.ttufo.com/($1)/($2)/($3).htm($5)");
replace = "($1)($3)";
string s = boost::regex_replace( target,
reg,
replace,
boost::match_default | boost::format_all);
cout << "test replace 1" << endl;
cout << s << endl;
cout << "test replace1 end" << endl;
}