我有一个文本例如:
我想吃一块馅饼,我想带狗出去,我想游泳(馅饼,狗,游泳)
我需要一个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)
Run Code Online (Sandbox Code Playgroud)
我需要的是:
I would like to eat a pie
I would like to take the dog out
I would like to swim(pie,dog,swim)
Run Code Online (Sandbox Code Playgroud)
您可以使用具有负前瞻的正则表达式(假设括号是平衡的且未转义):
str = str.replace(/,\s*(?![^()]*\))/g, '\n');
Run Code Online (Sandbox Code Playgroud)
(?![^()]*\))是负先行断言,我们没有一个)字符前面没有任何(或)在两者之间的字符.
码:
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'));Run Code Online (Sandbox Code Playgroud)