在 Linux 系統下,c++ 程序可借助
以下代碼示例演示了如何在 C++ 中應用正則表達式:
#include <iostream> #include <regex> #include <string> int main() { std::string text = "我的郵箱是 example@example.com,電話號碼是 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 << "郵箱地址: " << matches[1] << std::endl; } // 查找電話號碼 if (std::regex_search(text, matches, phone_regex)) { std::cout << "電話號碼: " << matches[1] << std::endl; } return 0; }
編譯該代碼,請使用 -std=c++++11 或更高版本標準編譯選項:
g++ -std=c++11 main.cpp -o main
運行編譯后的可執行文件:
立即學習“C++免費學習筆記(深入)”;
./main
程序輸出結果將顯示找到的郵箱地址和電話號碼。
本例中,我們使用了兩個正則表達式分別匹配郵箱地址和電話號碼。std::regex_search 函數用于在文本字符串中查找匹配的子字符串。如果找到匹配項,則匹配結果將存儲在 std::smatch 對象中,方便我們提取匹配文本。