Hello! 欢迎来到小浪云!


C++在Linux中如何使用正则表达式


avatar
小浪云 2025-02-20 14

C++在Linux中如何使用正则表达式

Linux 系统下,c++ 程序可借助 库高效处理正则表达式。该库是 C++11 的标准组件,请确保您的编译器支持 C++11 或更高版本。

以下代码示例演示了如何在 C++ 中应用正则表达式

#include <iostream> #include <regex> #include <string>  int main() {     std::string text = "我的邮箱是 example@example.com,电话号码是 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 << "邮箱地址: " << matches[1] << std::endl;     }      // 查找电话号码     if (std::regex_search(text, matches, phone_regex)) {         std::cout << "电话号码: " << matches[1] << std::endl;     }      return 0; }

编译该代码,请使用 -std=c++++11 或更高版本标准编译选项:

g++ -std=c++11 main.cpp -o main

运行编译后的可执行文件:

立即学习C++免费学习笔记(深入)”;

./main

程序输出结果将显示找到的邮箱地址和电话号码。

本例中,我们使用了两个正则表达式分别匹配邮箱地址和电话号码。std::regex_search 函数用于在文本字符串中查找匹配的子字符串。如果找到匹配项,则匹配结果将存储在 std::smatch 对象中,方便我们提取匹配文本。

相关阅读