溫馨提示×

c++ string匹配怎樣處理正則表達式

c++
小樊
82
2024-09-25 08:48:13
欄目: 編程語言

在 C++ 中,你可以使用 <regex> 庫來處理正則表達式

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

int main() {
    std::string input = "Hello, my email is example@example.com and my phone number is 123-456-7890.";
    
    // 創(chuàng)建一個正則表達式對象,用于匹配郵箱地址
    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(input.cbegin());
    while (std::regex_search(searchStart, input.cend(), matches, email_regex)) {
        std::cout << "Found email: " << matches[0] << std::endl;
        searchStart = matches.suffix().first;
    }
    
    // 創(chuàng)建一個正則表達式對象,用于匹配電話號碼
    std::regex phone_regex(R"(\d{3}-\d{3}-\d{4})");
    
    // 在輸入字符串中查找所有匹配的電話號碼
    searchStart = input.cbegin();
    while (std::regex_search(searchStart, input.cend(), matches, phone_regex)) {
        std::cout << "Found phone number: " << matches[0] << std::endl;
        searchStart = matches.suffix().first;
    }
    
    return 0;
}

在這個示例中,我們創(chuàng)建了兩個正則表達式對象:email_regex 用于匹配電子郵件地址,phone_regex 用于匹配電話號碼。然后我們使用 std::regex_search() 函數在輸入字符串中查找所有匹配的郵箱地址和電話號碼,并將它們打印出來。

0