溫馨提示×

C++中regex如何匹配括號

c++
小億
206
2024-02-28 12:25:17
欄目: 編程語言

在C++中,可以使用正則表達式來匹配括號。下面是一個示例代碼,用于匹配包含括號的字符串:

#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;
}

在上面的代碼中,我們定義了一個正則表達式 \\([^()]*\\) 來匹配括號內的內容。然后我們使用 std::regex_search 函數來查找字符串中滿足正則表達式的部分,并使用 std::smatch 對象來保存匹配的結果。最后輸出匹配到的內容。

注意,正則表達式中的 ( ) 需要轉義為 \\( \\),以保證它們被當作普通字符處理,而不是分組符號。

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