JAVASCRIPT
Extract Content within Parentheses
Extract all substrings enclosed within balanced parentheses `()` from a given text, useful for parsing specific data blocks.
function extractParenthesizedContent(text) {
// This regex extracts non-nested content. For deeply nested structures, a more complex parser is needed.
const regex = /\(([^)]+)\)/g;
const matches = [];
let match;
while ((match = regex.exec(text)) !== null) {
matches.push(match[1]);
}
return matches;
}
const text1 = "This is a sentence (with some extra info) and another (piece of data).";
console.log(extractParenthesizedContent(text1)); // ["with some extra info", "piece of data"]
const text2 = "No parentheses here.";
console.log(extractParenthesizedContent(text2)); // []
How it works: The regex `/\(([^)]+)\)/g` searches for content wrapped in literal parentheses. `\(` and `\)` match the literal parentheses characters. `([^)]+)` is a capturing group that matches one or more `+` characters that are *not* a closing parenthesis `[^)]`. The `g` flag ensures that all occurrences within the string are found, and `regex.exec()` is used in a loop to collect all matches.