在 Ubuntu 上使用 C++ 正则表达式,你需要包含 <regex>
头文件。C++11 标准引入了对正则表达式的支持,所以请确保你的编译器支持 C++11 或更高版本。
下面是一个简单的例子,展示了如何在 Ubuntu 上使用 C++ 正则表达式:
#include <iostream> #include <string> #include <regex> int main() { std::string text = "Hello, my name is John Doe."; std::regex pattern("John Doe"); if (std::regex_search(text, pattern)) { std::cout << "Pattern found in text." << std::endl; } else { std::cout << "Pattern not found in text." << std::endl; } return 0; }
要编译这个程序,请使用以下命令:
g++ -std=c++11 main.cpp -o main
然后运行生成的可执行文件:
./main
这将输出 “Pattern found in text.”,因为 “John Doe” 出现在给定的文本中。
你可以根据需要修改正则表达式和文本。C++ <regex>
库提供了许多功能,如匹配、搜索、替换等。要了解更多关于 C++ 正则表达式的信息,请查阅 cppreference.com。