溫馨提示×

c++ string匹配能否實現(xiàn)多模式匹配

c++
小樊
81
2024-09-25 08:49:13
欄目: 編程語言

是的,C++中的std::regex庫可以實現(xiàn)多模式匹配。你可以使用|運算符來表示多個模式之間的“或”關(guān)系。下面是一個簡單的示例:

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

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

    // 創(chuàng)建一個正則表達式對象,包含兩個模式
    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;
}

在這個示例中,我們創(chuàng)建了一個正則表達式對象pattern,它包含兩個模式:quicklazy。然后我們使用std::sregex_iterator遍歷輸入字符串input,查找與模式匹配的子串。最后,我們輸出所有匹配的子串。

0