C++ Regex: Matching Parentheses Guide

In C++, regular expressions can be used to match parentheses. Below is an example code for matching strings containing parentheses.

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

In the code above, we define a regular expression \\([^()]*\\) to match the content within parentheses. Then we use the std::regex_search function to search for the parts of the string that match the regular expression, and use the std::smatch object to store the matching results. Finally, we output the matched content.

Please note that in regular expressions, the parentheses ( ) need to be escaped as \\( \\) to ensure they are treated as ordinary characters, not grouping symbols.

bannerAds