溫馨提示×

Linux下C++如何使用正則表達式

小樊
73
2025-02-28 22:02:55
欄目: 編程語言

在 Linux 下,C++ 可以使用 <regex> 庫來處理正則表達式。<regex> 是 C++11 標準庫的一部分,因此你需要使用支持 C++11 或更高版本的編譯器來編譯你的代碼。

下面是一個簡單的示例,展示了如何在 C++ 中使用正則表達式:

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

int main() {
    std::string text = "Hello, my email is example@example.com and my phone number is 123-456-7890.";
    std::regex email_regex(R"((\w+@\w+\.\w+))");
    std::regex phone_regex(R"((\d{3}-\d{3}-\d{4}))");

    std::smatch matches;

    // 查找電子郵件地址
    if (std::regex_search(text, matches, email_regex)) {
        std::cout << "Found email: " << matches[0] << std::endl;
    } else {
        std::cout << "Email not found." << std::endl;
    }

    // 查找電話號碼
    if (std::regex_search(text, matches, phone_regex)) {
        std::cout << "Found phone number: " << matches[0] << std::endl;
    } else {
        std::cout << "Phone number not found." << std::endl;
    }

    return 0;
}

在這個示例中,我們使用了兩個正則表達式:一個用于匹配電子郵件地址,另一個用于匹配電話號碼。std::regex_search 函數用于在文本中查找與正則表達式匹配的子串。如果找到匹配項,它將返回 true,并將匹配項存儲在 std::smatch 對象中。

要編譯此代碼,請確保使用支持 C++11 或更高版本的編譯器,并添加 -std=c++11(或更高版本)標志。例如,使用 g++ 編譯器:

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

然后運行生成的可執行文件:

./main

這將輸出:

Found email: example@example.com
Found phone number: 123-456-7890

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女