GorvGoyl
GorvGoyl

Reputation: 49280

Ignore white-space when capturing text between parentheses

I've managed to get the text inside ( ) parenthesis. Also, I'm able to trim the leading whitespace but I can't get rid of the trailing whitespace.

For text node ( t-vr0wkjqky55s9mlh2rtt0u301(asdad) ) { }

my regex \(\s*(.*)\) is returning t-vr0wkjqky55s9mlh2rtt0u301(asdad) / (notice the trailing whitespace and ignore /).

Here's the running code https://regex101.com/r/uMfr4G/1/

And a live example of the problem:

var str = "node     (    t-vr0wkjqky55s9mlh2rtt0u301(asdad)   ) { }";
var rex = /\(\s*(.*)\)/;
console.log("[" + rex.exec(str)[1] + "]");

Upvotes: 3

Views: 287

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626929

You may use

/\(\s*(.*\S)\s*\)/

See the regex demo.

Details

  • \( - a (
  • \s* - 0+ whitespace chars
  • (.*\S) - Group 1: any 0+ chars other than line break chars, as many as possible (.*), and then any non-whitespace char (maybe, instead of \S, [^)\s] / [^()\s] can be a better option here to exclude matching parentheses)
  • \s* - 0+ whitespace chars
  • \) - a ).

Updated snippet:

var str = "node     (    t-vr0wkjqky55s9mlh2rtt0u301(asdad)   ) { }";
var rex = /\(\s*(.*\S)\s*\)/;
console.log("[" + rex.exec(str)[1] + "]");

Upvotes: 2

Hassan Imam
Hassan Imam

Reputation: 22534

Use this \(\s*(\S*)\s*\)

var str = "node     (    t-vr0wkjqky55s9mlh2rtt0u301(asdad)   ) { }";
var rex = /\(\s*(\S*)\s*\)/;
console.log("[" + rex.exec(str)[1] + "]");

Upvotes: 0

Related Questions