1

Consider the following string:

(first group) (second group) (third group)hello example (words(more words) here) something

The desired matches would be:

(first group)
(second group)
(third group)
(words(more words) here)

I've tried to build a regex as follows:

/\(.*?\)/g

But it matches the following:

(first group)
(second group)
(third group)
(words(more words)

Any ideas?

3 Answers 3

2

Since this needs to be done in JavaScript, we have two options:

a) specify a pattern with a fixed nesting depth (this seems to be case here):

\((?:[^()]|\([^()]*\))*\)

const regex = /\((?:[^()]|\([^()]*\))*\)/g;
const str = `(first group) (econd group) (third group)hello example (words(more words) here) something`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

Or use XRegexp (or a similar library) that implements recursive matching:

const str = `(first group) (econd group) (third group)hello example (words(more words) here) something`;
console.log(XRegExp.matchRecursive(str, '\\(', '\\)', 'g'));
<script src="https://cdn.jsdelivr.net/npm/[email protected]/xregexp-all.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

0

Maybe this could work in your case. \((?:[^()]|\([^()]+\))+\).

Side note: Not too proud of how I did this.

Comments

0

Can you please try out the below regular expression which uses recursion

\(([^()]|(?R))*\)

2 Comments

Invalid regular expression: Invalid group.
The escape sequence backslash was not getting posted for some reason. Please add like \(([^()]|(?R))*\).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.