Matty
Matty

Reputation: 83

Split string with ignore special RegEx substring

I need split the string, split character is "," but must skip content in "("...")".

const paramString = "gyro (param1, param2), proximity, Ultra Wideband (UWB) support, compass";

const paramArr = paramString.match(/[^(\)\,]+(\(.+?\))?/g).map( item => item.trim() ); 

In my result is paramArr[2] bad.

[ "gyro (param1, param2)", "proximity", "Ultra Wideband (UWB)", "support", "compass" ]

I need result:

[ "gyro (param1, param2)", "proximity", "Ultra Wideband (UWB) support", "compass" ]

Please advise how update my RegEx.

Upvotes: 1

Views: 161

Answers (2)

Meena Pintu
Meena Pintu

Reputation: 152

Try below mentioned regx , this will break your string in expected tokens only.

/[\w\ ]+(\([^)]*\))?(\ \w+)?/gi

The regx breaks your string in following tokens .

gyro (param1, param2)
 proximity
 Ultra Wideband (UWB) support
 compass

Please follow the link for live demo of the regx :

https://regex101.com/r/yCYHgw/1

https://regex101.com/r/yCYHgw/2


(updated, regx to work only with non nested )

Upvotes: 1

Amir MB
Amir MB

Reputation: 3418

You should use negative lookahead. You are basically selecting all commas (with spaces after them to trim them) that are not followed by a ) if there is no ( before it:

const paramString = "gyro (param1, param2), proximity, Ultra Wideband (UWB) support, compass";
const paramArr = paramString.split(/,\s*(?![^(]*\))/);

console.log(paramArr);

NOTE: it won't work for nested parentheses. It will fail in the following scenario:

const paramString = "gyro (param1, (param2)), proximity, Ultra Wideband (UWB) support, compass";

Upvotes: 2

Related Questions