c++

c++ string匹配能否实现多模式匹配

小樊
81
2024-09-25 08:49:13
栏目: 编程语言

是的,C++中的std::regex库可以实现多模式匹配。你可以使用|运算符来表示多个模式之间的“或”关系。下面是一个简单的示例:

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

int main() {
    std::string input = "The quick brown fox jumps over the lazy dog";

    // 创建一个正则表达式对象,包含两个模式
    std::regex pattern("(quick|lazy)");

    // 使用std::sregex_iterator遍历输入字符串,查找与模式匹配的子串
    std::sregex_iterator it(input.begin(), input.end(), pattern);
    std::sregex_iterator end;

    // 输出所有匹配的子串
    while (it != end) {
        std::cout << "Match: " << *it << std::endl;
        ++it;
    }

    return 0;
}

在这个示例中,我们创建了一个正则表达式对象pattern,它包含两个模式:quicklazy。然后我们使用std::sregex_iterator遍历输入字符串input,查找与模式匹配的子串。最后,我们输出所有匹配的子串。

0
看了该问题的人还看了