在 CentOS 系统中,C++ 正则表达式的应用主要依赖于 <regex> 头文件。C++11 标准引入了 <regex> 库,提供了对正则表达式的支持。以下是一个简单的示例,展示了如何在 CentOS 系统中使用 C++ 正则表达式:
-std=c++11 或 -std=c++14 或 -std=c++17 等选项启用 C++11 支持。例如,使用 g++ 编译器:g++ -std=c++11 main.cpp -o main
main.cpp 的文件,并添加以下代码:#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;
}
这个示例程序首先包含了 <iostream>、<regex> 和 <string> 头文件。然后,它定义了一个包含文本的字符串 text,以及两个正则表达式:一个用于匹配电子邮件地址,另一个用于匹配电话号码。接下来,程序使用 std::regex_search 函数在文本中搜索匹配项,并将结果存储在 std::smatch 对象中。最后,程序输出找到的电子邮件地址和电话号码。
g++ -std=c++11 main.cpp -o main
./main
输出结果:
Email found: example@example.com
Phone number found: 123-456-7890
这就是在 CentOS 系统中使用 C++ 正则表达式的一个简单示例。你可以根据需要修改正则表达式和文本,以实现更复杂的匹配和搜索功能。