1

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.

2 Answers 2

2

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";
Sign up to request clarification or add additional context in comments.

Comments

1

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 )

2 Comments

I think your solution is not perfect for nested ones. It can take care continuous ) but cannot not continuous ) like gyro (param1, (param2, param3), param4). I think perfect solution for nested one is not possible with regex. In addition, you need no escape for space. So space is enough instead of \space.
yes, that's right it not perfect for nested all possible nested one, I think requester can check if solution for nested ones is needed or not . if it more of nested than I think there is need to have custom logic implemented to handle this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.