Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,880 questions

51,806 answers

573 users

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
...