Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

regex - Javascript: Splitting a string by comma but ignoring commas in quotes

I have a string like following

var str="A,B,C,E,'F,G,bb',H,'I9,I8',J,K"

I'd like to split the string on commas. However, in the case where something is inside single quotation marks, I need it to both ignore commas as following.

 A
 B
 C
 E
 F,G,bb
 H
 I9,I8
 J
 K
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)
> str.match(/('[^']+'|[^,]+)/g)
["A", "B", "C", "E", "'F,G,bb'", "H", "'I9,I8'", "J", "K"]

Though you requested this, you may not accounted for corner-cases where for example:

  • 'bob's' is a string where ' is escaped
  • a,',c
  • a,,b
  • a,b,
  • ,a,b
  • a,b,'
  • ',a,b
  • ',a,b,c,'

Some of the above are handled correctly by this; others are not. I highly recommend that people use a library that has thought this through, to avoid things such as security vulnerabilities or subtle bugs, now or in the future (if you expand your code, or if other people use it).


Explanation of the RegEx:

  • ('[^']+'|[^,]+) - means match either '[^']+' or [^,]+
  • '[^']+' means quote...one-or-more non-quotes...quote.
  • [^,]+ means one-or-more non-commas

Note: by consuming the quoted string before the unquoted string, we make the parsing of the unquoted string case easier.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...