在 C++ 中,可以使用 regex
庫來實(shí)現(xiàn)多個(gè)模式的字符串匹配。下面是一個(gè)簡單的例子,展示了如何使用正則表達(dá)式進(jìn)行多模式匹配:
#include <iostream>
#include <string>
#include <regex>
int main() {
std::string input = "I have 100 books and 20 pens.";
// 創(chuàng)建一個(gè)包含多個(gè)模式的 regex 對(duì)象
std::regex patterns("([0-9]+)|([a-zA-Z]+)");
// 使用迭代器遍歷所有匹配的結(jié)果
std::sregex_iterator it(input.begin(), input.end(), patterns);
std::sregex_iterator end;
// 輸出所有匹配的結(jié)果
while (it != end) {
std::smatch match = *it;
std::cout << "Match: " << match.str() << std::endl;
++it;
}
return 0;
}
在這個(gè)例子中,我們創(chuàng)建了一個(gè)正則表達(dá)式對(duì)象 patterns
,它包含了兩個(gè)模式:一個(gè)用于匹配數(shù)字,另一個(gè)用于匹配字母。然后,我們使用 std::sregex_iterator
遍歷輸入字符串中的所有匹配項(xiàng),并將它們輸出到控制臺(tái)。
這只是一個(gè)簡單的例子,你可以根據(jù)需要修改正則表達(dá)式和匹配邏輯來實(shí)現(xiàn)更復(fù)雜的多模式匹配。