JavaScript环境下如何匹配含指定关键词的括号内全部内容?
Hey there! Let's work through this regex problem you're stuck on—since you're in a JavaScript environment, we need a solution that handles those tricky nested parentheses and only grabs the content inside brackets that include the word "green".
First, let's break down what went wrong with your earlier attempts
- Your first regex
/(.*?green.*?/)had two main issues: you didn't escape the parentheses (they're special regex characters, so you need\(and\)to match literal brackets), and using/as a delimiter here was confusing (you probably meant to match parentheses, not slashes). - The second regex
/(.*green.*/)suffered from the same unescaped parentheses problem, plus the greedy.*matched the entire string instead of stopping at the correct closing bracket.
The Correct Regex for Nested Parentheses
Since your target strings have nested parentheses (like mint (light) green pants), we need a regex that can balance those brackets and check for the presence of "green" inside them. Modern JavaScript (Chrome, Node.js 10+, etc.) supports recursive regex, which is perfect for this:
const regex = /\((?=(?:[^()]|(?R))*green)((?:[^()]|(?R))*)\)/g;
Let's break down what each part does:
\(: Matches the opening literal parenthesis(?=(?:[^()]|(?R))*green): A positive lookahead that ensures the content inside the parentheses (including nested brackets) contains the word "green"(?:[^()]|(?R))*: Non-capturing group that matches either non-parenthesis characters or recursively matches the entire regex (to handle nested brackets)
((?:[^()]|(?R))*): Capturing group that grabs all the content inside the outer parentheses (including nested ones)\): Matches the closing literal parenthesisg: Global flag to find all matches in the string
How to Use It in JavaScript
Here's a complete code example to extract your desired results:
const inputStr = "OSDfhosjdjakjdnvkjndkfvjelkrjejrijrvrvrjvnkrjvnkn(mint (light) green pants)shdbfhsbdhfbsjd(couch)hvbjshdbvjhsbdfbjs(forest (dark) (stained) green shirt) sjdfjsdhfjshkdfjskdjfksjdfhfskdjf(table)"; const greenParenthesesRegex = /\((?=(?:[^()]|(?R))*green)((?:[^()]|(?R))*)\)/g; const matches = []; let currentMatch; // Loop through all matches and extract the captured content while ((currentMatch = greenParenthesesRegex.exec(inputStr)) !== null) { matches.push(currentMatch[1]); } console.log(matches); // Output: ["mint (light) green pants", "forest (dark) (stained) green shirt"]
Compatibility Note
If you need to support older JS environments that don't allow recursive regex ((?R)), you can use a more manual approach with a function to track bracket balance, but the recursive regex is the cleanest solution for modern setups.
内容的提问来源于stack exchange,提问作者Hexiva

