2017-07-31 16 views
1

我有例如文本:如何更換一個逗號外支架

我就喜歡吃餡餅,我想帶着狗出去,我想去游泳(餡餅,狗,游泳)

我需要一個JavaScript正則表達式,與() 之外的新線取代了,現在如果我使用.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) 

回答

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

大膽的假設。 –

+1

你釘了它,非常好 – sForSujit

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

該模式匹配:

  • \( - 一個)
  • | - - 或
  • (,) - 第1組一個(
  • [^)]* - 比)
  • \)其他0+字符:一個,
  • \s* - 0+空格(以「修剪」線前的空白)。

查看regex demo