在 Ubuntu 上使用 C++ 正則表達式庫非常簡單,因為這個庫已經作為 C++ 標準庫的一部分被包含進來。C++11 引入了 <regex> 頭文件,提供了對正則表達式的支持。下面是一個簡單的例子,演示了如何在 Ubuntu 上使用 C++ 和正則表達式:
-std=c++11 或 -std=c++14 或 -std=c++17 等選項來啟用相應的標準。例如,使用 g++ 編譯器:g++ -std=c++11 your_file.cpp -o your_program
your_file.cpp 的 C++ 源文件,并在其中編寫以下代碼:#include <iostream>
#include <regex>
#include <string>
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 << "Email found: " << matches[0] << std::endl;
} else {
std::cout << "Email not found." << std::endl;
}
if (std::regex_search(text, matches, phone_regex)) {
std::cout << "Phone number found: " << matches[0] << std::endl;
} else {
std::cout << "Phone number not found." << std::endl;
}
return 0;
}
這個程序會在給定的文本中查找電子郵件地址和電話號碼,并將它們打印出來。
g++ -std=c++11 your_file.cpp -o your_program
./your_program
你應該會看到以下輸出:
Email found: example@example.com
Phone number found: 123-456-7890
這就是在 Ubuntu 上使用 C++ 正則表達式的基本方法。你可以根據需要修改正則表達式以匹配不同的模式。