您可以通过以下三个步骤完成该操作:
- 使用正则表达式全局替换将所有字符串的内容提取到一个辅助表中。
- 进行逗号翻译。
- 使用正则表达式全局替换将字符串的内容交换回来。
下面是代码:
var sideTable = [];
myString = myString.replace(
/"(?:[^"\\]|\\.)*"/g,
function (_) {
var index = sideTable.length;
sideTable[index] = _;
return '"' + index + '"';
});
// Step 2, replace commas with newlines
myString = myString.replace(/,/g, "\n");
// Step 3, swap the string bodies back
myString = myString.replace(/"(\d+)"/g,
function (_, index) {
return sideTable[index];
});
如果您设置后运行该操作
myString = '{:a "ab,cd, efg", :b "ab,def, egf,", :c "Conjecture"}'
你应该获取
{:a "ab,cd, efg"
:b "ab,def, egf,"
:c "Conjecture"}
这个方法可行,因为在第一步之后,
myString = '{:a "0", :b "1", :c "2"}'
sideTable = ["ab,cd, efg", "ab,def, egf,", "Conjecture"];
因此,myString中唯一的逗号都在字符串外。然后,第二步将逗号转换为换行符:
myString = '{:a "0"\n :b "1"\n :c "2"}'
最后,我们将仅包含数字的字符串替换为其原始内容。
?:
:\+(?=(?:[^"\\]*(?:\\.|"(?:[^"\\]*\\.)*[^"\\]*"))*[^"]*$)
- Azmisov''
中间有一个双引号'"'
... 这将导致字符串中双引号的数量是奇数。 - anson