【问题标题】:How to split complex string in to array?如何将复杂的字符串拆分为数组?
【发布时间】:2018-10-09 11:02:03
【问题描述】:

我有一个用逗号分隔的复杂字符串(可能包含逗号)。如何通过跳过内部逗号将字符串拆分为数组?

例如我有一个字符串:

"'test1 test2', 'test3', 123, \"test4\", null, \"test5 , test6 test7\", 'test8, test9','test8,test9' ,'test10 , test11', , , 'test12'"

我要获取数组:

["test1 test2", "test3", 123, "test4", null, ""test5 , test6 test7"", "test8, test9", "test8,test9", "test10 , test11", empty × 2, "test12"]

更新: 基于 cmets 我找到了一个实用的解决方案(感谢@NinaScholz):

.match(/(["'].*?["']|[^",\s]+)/g);

但是没有空字符串...嗯...我不确定它是否涵盖了所有可能的情况?

【问题讨论】:

  • 欢迎来到 SO。在这里,我们帮助您编写代码;我们不会为您完成任务。
  • 到目前为止你有什么尝试?
  • 可能是欺骗目标:stackoverflow.com/q/11456850
  • eval它(并面对后果)。
  • @Utkanos,我是否被要求做某事?

标签: javascript arrays regex split


【解决方案1】:

split() 方法用于将字符串拆分为子字符串数组,并返回新数组。

var str = "'test1 test2', 'test3', 123, \"test4\", null, \"test5 , test6 test7\", 'test8, test9','test8,test9' ,'test10 , test11', , , 'test12'";
var res = str.split(" ");
console.log(res)

check this link

【讨论】:

  • 不会产生预期的结果。
猜你喜欢
  • 1970-01-01
  • 2019-06-11
  • 1970-01-01
  • 1970-01-01
  • 2013-08-19
  • 1970-01-01
  • 1970-01-01
  • 2018-05-10
相关资源
最近更新 更多