在Linux中,C++可以使用<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 << "No email found." << std::endl;
}
// 查找電話號碼
if (std::regex_search(text, matches, phone_regex)) {
std::cout << "Found phone number: " << matches[0] << std::endl;
} else {
std::cout << "No phone number found." << std::endl;
}
return 0;
}
在這個例子中,我們包含了<regex>庫,并使用了std::regex類來定義正則表達式。我們使用std::regex_search函數在文本中查找匹配項,并將結果存儲在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