JavaScript中的split方法,逗号但不包括双引号。

huangapple go评论97阅读模式
英文:

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(/(?<!"),(?!")/);
}

huangapple
  • 本文由 发表于 2023年2月18日 23:33:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/75494386.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定