使用正则表达式捕获括号内文本时,如何去除尾随空格?
Hey, let's break down why you're getting that trailing space in your capture and how to fix it properly.
Why the Trailing Space Happens
Your regex /\(\s*(.*)\)/ uses a greedy .* quantifier. This means it matches every character it can—including spaces and inner parentheses—until it hits the very last closing parenthesis in the string. In your example, that includes the space right before the outer ), which is why your result has that trailing space.
Solution 1: Regex for Balanced Parentheses (Works with Nested Pairs)
Since your content includes nested parentheses (like (asdad) inside the outer pair), we need a regex that targets the matching closing parenthesis without grabbing extra spaces. Here's the fix:
var str = "node ( t-vr0wkjqky55s9mlh2rtt0u301(asdad) ) { }"; var rex = /\(\s*([^()]*(?:\([^()]*\)[^()]*)*)\s*\)/; console.log("[" + rex.exec(str)[1] + "]"); // Output: [t-vr0wkjqky55s9mlh2rtt0u301(asdad)]
Here's a breakdown of how this regex works:
\(\s*: Matches the opening parenthesis and any leading spaces- The captured group
([^()]*(?:\([^()]*\)[^()]*)*):[^()]*: Grabs any characters that aren't parentheses(?:\([^()]*\)[^()]*)*: Handles nested parentheses by matching a full inner pair, then any non-parenthesis characters, repeating as needed
\s*\): Matches any trailing spaces right before the closing parenthesis (so they don't end up in your capture)
Solution 2: Quick Fix with String Trimming
If you prefer a simpler approach and don't mind post-processing, use your original regex and trim the trailing spaces with JavaScript's trimEnd() method:
var str = "node ( t-vr0wkjqky55s9mlh2rtt0u301(asdad) ) { }"; var rex = /\(\s*(.*)\)/; // Your original regex var capturedText = rex.exec(str)[1]; console.log("[" + capturedText.trimEnd() + "]"); // Output: [t-vr0wkjqky55s9mlh2rtt0u301(asdad)]
If you know there are no nested parentheses in your content, you can also use a non-greedy regex to avoid capturing the outer space in the first place:
var rex = /\(\s*(.*?)\s*\)/; console.log("[" + rex.exec(str)[1] + "]"); // No trailing space here
内容的提问来源于stack exchange,提问作者GorvGoyl

