如何在括号

时间:2017-07-31 09:38:37

标签: javascript regex

我有一个例如文字:

  我想吃一块馅饼,我想带狗出去,我想游泳(馅饼,狗,游泳)

我需要一个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)

2 个答案:

答案 0 :(得分:5)

你可以使用带有负前瞻的正则表达式(假设括号是平衡的和非转义的):

str = str.replace(/,\s*(?![^()]*\))/g, '\n');

RegEx Demo

(?![^()]*\))是一个消极的先行者,断言我们前面没有)个字符,中间没有()个字符。

<强>代码:

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'));

答案 1 :(得分:2)

匹配(...)子字符串并匹配并捕获其他上下文中的,,以便在检查组1是否匹配后,稍后用换行符替换:

var rx = /\([^)]*\)|(,)\s*/g;
var s = "I would like to eat a pie,I would like to take the dog out, I would like to swim(pie,dog,swim)";
var result = s.replace(rx, function($0,$1) {
  return $1 ? "\n" : $1;
});
console.log(result);

模式匹配:

  • \( - (
  • [^)]* - 除)
  • 以外的0个字符
  • \) - )
  • | - 或
  • (,) - 第1组:,字符
  • \s* - 0+空格(以“修剪”线前面的空格)。

请参阅regex demo