c++ string匹配如何支持正則表達(dá)式

c++
小樊
81
2024-09-25 07:35:14

C++的<regex>庫(kù)支持正則表達(dá)式。你可以使用std::regex類來創(chuàng)建一個(gè)正則表達(dá)式對(duì)象,然后使用它的成員函數(shù)來執(zhí)行匹配操作。

下面是一個(gè)簡(jiǎn)單的示例,演示如何使用C++的<regex>庫(kù)進(jìn)行正則表達(dá)式匹配:

#include <iostream>
#include <string>
#include <regex>

int main() {
    std::string str = "Hello, my email is example@example.com and my phone number is 123-456-7890";
    
    // 創(chuàng)建一個(gè)正則表達(dá)式對(duì)象,匹配郵箱地址
    std::regex email_regex(R"(\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b)");
    
    // 在字符串中查找所有匹配的郵箱地址
    std::smatch matches;
    std::string::const_iterator searchStart(str.cbegin());
    while (std::regex_search(searchStart, str.cend(), matches, email_regex)) {
        std::cout << "Found email: " << matches[0] << std::endl;
        searchStart = matches.suffix().first;
    }
    
    // 創(chuàng)建一個(gè)正則表達(dá)式對(duì)象,匹配電話號(hào)碼
    std::regex phone_regex(R"(\d{3}-\d{3}-\d{4})");
    
    // 在字符串中查找所有匹配的電話號(hào)碼
    searchStart = str.cbegin();
    while (std::regex_search(searchStart, str.cend(), matches, phone_regex)) {
        std::cout << "Found phone number: " << matches[0] << std::endl;
        searchStart = matches.suffix().first;
    }
    
    return 0;
}

在上面的示例中,我們創(chuàng)建了兩個(gè)正則表達(dá)式對(duì)象:email_regex用于匹配郵箱地址,phone_regex用于匹配電話號(hào)碼。然后,我們使用std::regex_search函數(shù)在字符串str中查找所有匹配的郵箱地址和電話號(hào)碼,并將它們打印出來。

注意,正則表達(dá)式中的特殊字符需要進(jìn)行轉(zhuǎn)義。例如,在上面的示例中,我們?cè)谡齽t表達(dá)式中使用了\b來表示單詞邊界,使用了\.來表示點(diǎn)字符。這是因?yàn)檫@些字符在正則表達(dá)式中具有特殊的含義。

0