C++之正則表達式


正則表達式是獨立與任何語言本身的一個很大的話題。在C++中,regex就是涉及到正則表達式的內容。

 

[a-z]+.\txt:在這個正則表達式中,[a-z]標識匹配一個小寫字母,+可以是前面的表達式匹配多次,因此[a-z]+能夠匹配一個小寫字母組成的字符串。

在正則表達式中的一個 . 表示匹配任意字符,而 \. 則表示匹配字符 . ,最后txt表示嚴格匹配txt三個字母。因此這個正則表達式索要匹配的內容就是由純小寫字母組成的文本文件。

 

regex_match用於匹配字符串和正則表達式,有很多不同的重載形式。最簡單一種形式就是傳入string以及一個regex進行匹配,當匹配成功,會返回一個true,否則返回一個false。

/*
regex.cpp
*/
#include<iostream>
#include<string>
#include<regex>
using namespace std;

int main()
{
    string fnames[] = {"foo.txt", "bar.txt", "test", "a0.txt", "AAA.txt"};
    std::regex txt_regex("[a-z]+\\.txt");
    for (const auto &fname: fnames)
    {
        cout << fname << ": " << regex_match(fname, txt_regex) << endl;
    }

    return 0;
}

 

編譯:

g++ regex.cpp -o regex -std=c++11

 

運行結果:

foo.txt: 1

bar.txt: 1

test: 0

a0.txt: 0

AAA.txt: 0

 

另一種常用的形式就是依次傳入 std::string/std::smatch/std::regex 三個參數,其中 std::smatch 的本質其實是 std::match_results,在標准庫中, std::smatch 被定義為了 std::match_results<std::string::const_iterator>,也就是一個子串迭代器類型的 match_results。使用 std::smatch 可以方便的對匹配的結果進行獲取,例如:

/*
regex_1.cpp
*/
#include <iostream>
#include <string>
#include <regex>

int main() {
    std::string fnames[] = {"foo.txt", "bar.txt", "test", "a0.txt", "AAA.txt"};
    std::regex base_regex("([a-z]+)\\.txt");
    std::smatch base_match;
    for(const auto &fname: fnames) {
        if (std::regex_match(fname, base_match, base_regex)) {
            // sub_match 的第一個元素匹配整個字符串
            // sub_match 的第二個元素匹配了第一個括號表達式
            if (base_match.size() == 2) {
                std::string base = base_match[1].str();
                std::cout << "sub-match[0]: " << base_match[0].str() << std::endl;
                std::cout << fname << " sub-match[1]: " << base << std::endl;
            }
        }
    }
}

 

運行結果:

sub-match[0]: foo.txt

foo.txt sub-match[1]: foo

sub-match[0]: bar.txt

bar.txt sub-match[1]: bar

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM