You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用正则表达式捕获括号内文本时,如何去除尾随空格?

Fixing Unwanted Trailing Spaces in Your Regex Capture

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:25:52