ubuntu

Ubuntu C++怎样使用正则表达式

小樊
48
2025-10-06 15:37:45
栏目: 编程语言

在Ubuntu上使用C++进行正则表达式操作,你需要包含<regex>头文件。以下是一个简单的示例,展示了如何使用C++的正则表达式库:

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

int main() {
    // 要匹配的文本
    std::string text = "Hello, my name is John Doe and I am 30 years old.";

    // 正则表达式模式
    std::regex pattern(R"((\w+)\s(\w+))"); // 匹配两个单词,中间有一个空格

    // 使用std::sregex_iterator进行迭代匹配
    auto words_begin = std::sregex_iterator(text.begin(), text.end(), pattern);
    auto words_end = std::sregex_iterator();

    std::cout << "Found " << std::distance(words_begin, words_end) << " words:" << std::endl;

    for (std::sregex_iterator i = words_begin; i != words_end; ++i) {
        std::smatch match = *i;
        std::string match_str = match.str();
        std::cout << match_str << std::endl;
    }

    return 0;
}

要编译这个程序,请在终端中运行以下命令:

g++ -o regex_example regex_example.cpp

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

./regex_example

这个示例将输出:

Found 4 words:
Hello my
my name
name is
is John
John Doe
Doe and
and I
I am
am 30
30 years
years old

你可以根据需要修改正则表达式模式以匹配不同的文本。

0
看了该问题的人还看了