How to extract words wrapped in parentheses from a string using RegEx in C++

1 Answer

0 votes
#include <iostream>
#include <string>
#include <regex>
#include <vector>

std::vector<std::string> extractWordsInParentheses(const std::string& input) {
    std::vector<std::string> results;
    std::regex parenthesisRegex("\\(([^)]*?)\\)"); // Regex to match (word)
    std::smatch match;

    std::string::const_iterator searchStart(input.cbegin());
    while (std::regex_search(searchStart, input.cend(), match, parenthesisRegex)) {
        results.push_back(match[1]); // Extract the word inside parentheses
        searchStart = match.suffix().first; // Move the searchStart past the current match
    }

    return results;
}

int main() {
    std::string text = "This is a string (word1) with multiple (word2) parentheses (word3).";
    std::vector<std::string> words = extractWordsInParentheses(text);

    for (const auto& word : words) {
        std::cout << word << std::endl;
    }
}



/*
run:

word1
word2
word3

*/

 



answered Apr 9, 2025 by avibootz
...