在C++中,可以使用正則表達(dá)式來匹配括號(hào)。下面是一個(gè)示例代碼,用于匹配包含括號(hào)的字符串:
#include <iostream>
#include <regex>
int main() {
std::string str = "This is a (sample) string with (parentheses)";
std::regex regex("\\([^()]*\\)");
std::smatch match;
while (std::regex_search(str, match, regex)) {
for (auto m : match) {
std::cout << m << std::endl;
}
str = match.suffix().str();
}
return 0;
}
在上面的代碼中,我們定義了一個(gè)正則表達(dá)式 \\([^()]*\\)
來匹配括號(hào)內(nèi)的內(nèi)容。然后我們使用 std::regex_search
函數(shù)來查找字符串中滿足正則表達(dá)式的部分,并使用 std::smatch
對(duì)象來保存匹配的結(jié)果。最后輸出匹配到的內(nèi)容。
注意,正則表達(dá)式中的 ( )
需要轉(zhuǎn)義為 \\( \\)
,以保證它們被當(dāng)作普通字符處理,而不是分組符號(hào)。