Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

regex - Javascript split by spaces but not those in quotes

The goal is to split a string at the spaces but not split the text data that is in quotes or separate that from the adjacent text.

The input is effectively a string that contains a list of value pairs. If the value value contains a space it is enclosed in quotes. I need a function that returns an array of value-pair elements as per the example below:

Example Input:

'a:0 b:1 moo:"foo bar" c:2'

Expected result:

a:0,b:1,moo:foo bar,c:2 (An array of length 4)

I have checked through a load of other questions but none of them (I found) seem to cope with my issue. Most seem to split at the space within the quotes or they split the 'moo:' and 'foo bar' into separate parts.

Any assistance would be greatly appreciated, Craig

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use this regex for split:

var s = 'a:0 b:1 moo:"foo bar" c:2';

var m = s.split(/ +(?=(?:(?:[^"]*"){2})*[^"]*$)/g);
//=> [a:0, b:1, moo:"foo bar", c:2]

RegEx Demo

It splits on spaces only if it is outside quotes by using a positive lookahead that makes sure there are even number of quotes after a space.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...