例如我有一段文字:
I would like to eat a pie, I would like to take the dog out, I would like to swim (pie, dog, swim)
我需要一个用 ()
之外的新行替换 ,
的 JavaScript RegEx
现在如果我使用 .replace(/,/g, "\n")
我会得到:
I would like to eat a pie
I would like to take the dog out
I would like to swim(pie
dog
out)
我需要的是:
I would like to eat a pie
I would like to take the dog out
I would like to swim(pie,dog,swim)
最佳答案
您可以使用负前瞻的正则表达式(假设括号是平衡的且未转义):
str = str.replace(/,\s*(?![^()]*\))/g, '\n');
(?![^()]*\))
是一个否定的前瞻性断言我们没有 )
字符前面没有任何 (
或 )
之间的字符。
代码:
var str = 'I would like to eat a pie,I would like to take the dog out, I would like to swim(pie,dog,swim)';
console.log(str.replace(/,\s*(?![^()]*\))/g, '\n'));
关于javascript - 如何替换括号外的一个逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45412294/