boost 正則表達(dá)式 regex

環(huán)境安裝

如果在引用boost regex出現(xiàn)連接錯(cuò)誤,但是引用其他的庫卻沒有這個(gè)錯(cuò)誤,這是因?yàn)閷?duì)于boost來說,是免編譯的,但是,正則這個(gè)庫 是需要單獨(dú)編譯和使用的。簡單的辦法就是 直接將boost庫全部編譯,然后 找到正則的lib,編譯時(shí)候引用進(jìn)去。

代碼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;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容