Separate a string with spaces, but not in brackets

I have a line like this foo bar(5) baz(0, 3) , and you need to break it into pieces based on spaces between them. Therefore, the result should look like this: ['foo', 'bar(5)', 'baz(0, 3)'] .

I tried something like this:

 var str = 'foo bar(5) baz(0, 3)'; str.split(' '); // => ['foo', 'bar(5)', 'baz(0,', '3)'] 

As you can see, the result is not what I expect ... Any ideas how to break it down correctly? I think this is a twist for RegExp -gurus here ...

Update

A simple way could be to replace everyone with:

 str.replace(/, /g, ',').split(' '); 

But it doesn’t look very beautiful for me ...

+4
source share
1 answer

You can use .match for this.

 str.match(/\w+(\(.*?\))?/g) => ["foo", "bar(5)", "baz(0, 3)"] 
+4
source

Source: https://habr.com/ru/post/1496507/


All Articles