英文:
javascript split method comma but without double quotes
问题
我有一个字符串,想要通过逗号,
分割它,但我的字符串中还包含","
,我希望忽略它,简而言之,我只想在没有双引号的情况下分割逗号,
。
这是我用来测试的代码:
function splitByCommas(str) {
return str.split(/,(?=(?:[:""]*"[^"]*")*[^"]*$)/);
}
上述函数的结果:
console.log(splitByCommas('gango.cs.{"test","asfasf"},ratings.eq.5,name.eq.kings}'));
函数输出的结果是 [ 'gango.cs.{"test"', '"asfasf"}', 'ratings.eq.5', 'name.eq.kings}' ]
我期望的输出是 [ 'gango.cs.{"test","asfasf"}', 'ratings.eq.5', 'name.eq.kings}' ]
有人知道如何获得我期望的输出吗?
英文:
I have a string and want to split it by comma ,
but my string also has ","
which I want ignored, so in short I want to split only where there's ,
without double quotes.
This is the code I'm testing it with
function splitByCommas(str) {
return str.split(/,(?=(?:[:""]*"[^"]*")*[^"]*$)/);
}
Results from the function above:
console.log(splitByCommas('gango.cs.{"test","asfasf"},ratings.eq.5,name.eq.kings}'));
What the function outputs [ 'gango.cs.{"test"', '"asfasf"}', 'ratings.eq.5', 'name.eq.kings}' ]
My desired output [ 'gango.cs.{"test","asfasf"}', 'ratings.eq.5', 'name.eq.kings}' ]
Anyone might have a hint on how to get my desired output?
答案1
得分: 1
使用 /(?<!"),(?!")/
正则表达式。
我已测试并确认以下代码有效。
function splitByCommas(str) {
return str.split(/(?<!"),(?!")/);
}
英文:
Use /(?<!"),(?!")/
regex.
I've tested and confirmed the following code is working.
function splitByCommas(str) {
return str.split(/(?<!"),(?!")/);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论