在 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++ 正则表达式的基本方法。你可以根据需要修改正则表达式以匹配不同的模式。