CodexBloom - Programming Q&A Platform

Regex Not Capturing Nested Parentheses in JavaScript - advanced patterns with Match Groups

πŸ‘€ Views: 99 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-11
regex javascript string-manipulation JavaScript

I'm not sure how to approach I'm trying to extract substrings enclosed in nested parentheses using regex in JavaScript, but I'm running into issues with capturing groups... My input string looks like this: ``` const input = "This is a test (with (nested) parentheses) and (another (example)) here."; ``` I want to capture the full content within the outermost parentheses, including any nested parentheses. I tried using the regex pattern: ``` const regex = /\(([^()]*|\([^()]*\))*\)/g; ``` However, when I run the following code: ``` const matches = input.match(regex); console.log(matches); ``` I expected to get an array with the full outer parentheses captured, but instead, I get: ``` [ '(with (nested) parentheses)', '(another (example))' ] ``` I don’t know how to adjust the regex to capture the entire substring from the outermost parentheses while still handling the nested ones properly. Additionally, I am aware that JavaScript's regex engine does not support recursive patterns directly. Is there a workaround, or should I consider a different approach for parsing this kind of nested structure? I'm currently using Node.js version 14.17.0. Any insights would be greatly appreciated! I'm working on a application that needs to handle this. Am I approaching this the right way?