Split string by whitespace but not within brackets

2019-04-09 15:14发布

问题:

I've a string like this foo bar(5) baz(0, 3) and need to split it into its parts based on spaces between each. So the result needs to 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 split it correctly? I think it's a turn for the RegExp-gurus here...

Update

A simple way could be to replace all , with ,:

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

But that doesn't look really pretty to me...

回答1:

You can use .match for this.

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