Manish Balodia
Manish Balodia

Reputation: 1877

regex match exclude bracket's string

I have following string and want to match string which are not in bracket"()".

i have tried it with following but it give match with bracket and i want to its inverse.

var str = '45.6 fl oz (456 g)';
console.log(str.match(/[\(]+[^\)]*\)/g));

Can any one help me? I want to following output:-

45.6 fl oz
(456 g)

Upvotes: 1

Views: 1436

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

You may split with /\s*(\([^()]*\))/:

var str = '45.6 fl oz (456 g)';
console.log(str.split(/\s*(\([^()]*\))/).filter(Boolean));
//Or, split with whitespaces before a (:
console.log(str.split(/\s*(?=\()/));

The pattern matches

  • \s* - 0+ whitespace chars
  • (\([^()]*\)) - Capturing group #1 (its value will be part of the resulting array):
    • \( - a (
    • [^()]* - any 0+ chars other than ( and )
    • \) - a ).

To exclude ( and ) in the result, adjust the capturing group boundaries: /\s*\(([^()]*)\)/.

The .filter(Boolean) will remove redundant leading/trailing empty array items that appear when the match is found at the start/end of the string.

The second variant, /\s*(?=\()/, just matches 0+ whitespace chars that are immediatley followed with a ( char (thanks to the (?=\() lookahead).

Upvotes: 2

31piy
31piy

Reputation: 23859

You need to capture two groups essentially; one, which targets the text not in () and another, which targets the text in ():

var str = '45.6 fl oz (456 g)';
console.log(str.match(/([^()])+|(\(.*\))/g).map(item => item.trim()));

Upvotes: 3

Related Questions