linux

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

小樊
49
2025-03-25 02:37:05
栏目: 编程语言

在 Linux 下,C++ 可以使用 <regex> 库来处理正则表达式。这是一个标准库,从 C++11 开始引入。以下是一个简单的示例,展示了如何在 C++ 中使用正则表达式:

#include <iostream>
#include <string>
#include <regex>

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 << "Found email: " << matches[0] << std::endl;
    } else {
        std::cout << "No email found." << std::endl;
    }

    // 查找电话号码
    if (std::regex_search(text, matches, phone_regex)) {
        std::cout << "Found phone number: " << matches[0] << std::endl;
    } else {
        std::cout << "No phone number found." << std::endl;
    }

    return 0;
}

在这个示例中,我们首先包含了 <regex> 头文件。然后,我们定义了一个包含文本的字符串 text,以及两个正则表达式:一个用于匹配电子邮件地址,另一个用于匹配电话号码。

接下来,我们使用 std::regex_search 函数在文本中查找与正则表达式匹配的子字符串。如果找到匹配项,我们将结果存储在 std::smatch 对象 matches 中,并输出匹配到的子字符串。

要编译这个示例,你需要使用支持 C++11 或更高版本的编译器。例如,使用 g++ 编译器,你可以使用以下命令:

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

然后运行生成的可执行文件:

./main

这将输出:

Found email: example@example.com
Found phone number: 123-456-7890

0
看了该问题的人还看了