regex match all between parentheses

Step 1: Include the regex library To use regular expressions in C++, you first need to include the <regex> library.

#include <regex>

Step 2: Declare a regular expression pattern Next, you need to declare a regular expression pattern that matches the text between parentheses. In this case, you can use the pattern \\((.*?)\\).

std::regex pattern("\\((.*?)\\)");
  • \\(: Matches an opening parenthesis.
  • (.*?): Matches any character zero or more times, lazily (non-greedy).
  • \\): Matches a closing parenthesis.

Step 3: Create a string to search Create a string that you want to search for matches. Let's assume the string is "(abc) (def) (ghi)".

std::string text = "(abc) (def) (ghi)";

Step 4: Define a std::smatch object Define a std::smatch object to store the matched results.

std::smatch matches;

Step 5: Use std::regex_search to find matches Use the std::regex_search function to search for matches in the string. Provide the string to search, the std::smatch object to store the results, and the regular expression pattern.

while (std::regex_search(text, matches, pattern)) {
    // Process each match here

    // After processing, update the string to search by removing the current match
    text = matches.suffix().str();
}

Step 6: Access the matched results Inside the loop, you can access the matched results using the std::smatch object. The matched text itself can be accessed using the str() function. To access the text between the parentheses, you can use matches[1].str().

std::string matchedText = matches.str(); // The entire match
std::string textBetweenParentheses = matches[1].str(); // Text between the parentheses

Step 7: Process each match Inside the loop, you can process each match according to your requirements. For example, you can print the matched text or store it in a container for further use.

std::cout << "Matched text: " << matchedText << std::endl;
std::cout << "Text between parentheses: " << textBetweenParentheses << std::endl;

Step 8: Update the string to search After processing each match, you need to update the string to search by removing the current match. This is done using the suffix() function of the std::smatch object.

text = matches.suffix().str();

Step 9: Repeat until no more matches The std::regex_search function will find the first match and then continue searching for subsequent matches in the remaining part of the string. The loop will continue until no more matches are found.

while (std::regex_search(text, matches, pattern)) {
    // Process each match here

    // After processing, update the string to search by removing the current match
    text = matches.suffix().str();
}