Javascript:使用逗号分隔字符串,但忽略逗号在引号中 [英] Javascript: Splitting a string by comma but ignoring commas in quotes

查看:721
本文介绍了Javascript:使用逗号分隔字符串,但忽略逗号在引号中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串如下

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

在逗号上的字符串;

 A
 B
 C
 E
 F,G,bb
 H
 I9,I8
 J
 K

请帮助,提前谢谢......

Please help ,Thank you in advance......

推荐答案

> 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:


  • \的'是一个字符串,其中'被转义

  • ,',c

  • a ,, b
  • a,b,
  • ,a,b

  • a,b,'

  • ',a,b

  • ',a,b,c,'

  • '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).

RegEx说明


  • ('[^'] +'| [^,] +) - 表示 '[^'] +' [^,] +

  • '[^'] +'表示 quote ...一个或多个非引号... quote

  • [^,] + 表示一个或多个非逗号

  • ('[^']+'|[^,]+) - 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.

这篇关于Javascript:使用逗号分隔字符串,但忽略逗号在引号中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆