溫馨提示×

c++ string匹配如何實現多模式匹配

c++
小樊
90
2024-09-25 07:39:15
欄目: 編程語言

在 C++ 中,可以使用 regex 庫來實現多個模式的字符串匹配。下面是一個簡單的例子,展示了如何使用正則表達式進行多模式匹配:

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

int main() {
    std::string input = "I have 100 books and 20 pens.";
    
    // 創建一個包含多個模式的 regex 對象
    std::regex patterns("([0-9]+)|([a-zA-Z]+)");

    // 使用迭代器遍歷所有匹配的結果
    std::sregex_iterator it(input.begin(), input.end(), patterns);
    std::sregex_iterator end;

    // 輸出所有匹配的結果
    while (it != end) {
        std::smatch match = *it;
        std::cout << "Match: " << match.str() << std::endl;
        ++it;
    }

    return 0;
}

在這個例子中,我們創建了一個正則表達式對象 patterns,它包含了兩個模式:一個用于匹配數字,另一個用于匹配字母。然后,我們使用 std::sregex_iterator 遍歷輸入字符串中的所有匹配項,并將它們輸出到控制臺。

這只是一個簡單的例子,你可以根據需要修改正則表達式和匹配邏輯來實現更復雜的多模式匹配。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女