在 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
遍歷輸入字符串中的所有匹配項,并將它們輸出到控制臺。
這只是一個簡單的例子,你可以根據需要修改正則表達式和匹配邏輯來實現更復雜的多模式匹配。