2016-01-26 63 views
1
之間的正則表達式

讓我們在下面的文本的Javascript括號

I want [this]. I want [this too]. I don't want \[this] 

說我想要的[]但不\[]之間的任何內容。我會怎麼做呢?到目前爲止,我有/\[([^\]]+)\]/gi。但它匹配了一切。

回答

0

使用這一個:/(?:^|[^\\])\[(.*?)\]/gi

這裏有一個工作示例:http://regexr.com/3clja

  • ?:非捕獲組
  • ​​Beggining字符串或任何東西,但[]
  • 之間 \
  • \[(.*?)\]匹配任何

這裏有一個片段:

var string = "[this i want]I want [this]. I want [this too]. I don't want \\[no]"; 
 
var regex = /(?:^|[^\\])\[(.*?)\]/gi; 
 
var match = null; 
 

 
document.write(string + "<br/><br/><b>Matches</b>:<br/> "); 
 
while(match = regex.exec(string)){ 
 
    document.write(match[1] + "<br/>"); 
 
}

+0

這不適用於'\ [no] [yes]'。 –

+0

是的,它確實與那種情況:) http://regexr.com/3clmj –

-1

/(?:[^\\]|^)\[([^\]]*)/g

內容是第一個捕捉組,$ 1

(?:^|[^\\])一行的開頭匹配或任何的不是斜線,不捕獲。

\[匹配一個開放的括號。

([^\]]*)捕獲的任何數量的不是封閉括號連續字符

\]匹配的右括號

+1

這不匹配[在開始的東西] –

+0

啊謝謝!修復。 – paulgoblin

0

使用此正則表達式,其中第一匹配\[]版本(但不捕獲它,從而「扔它扔掉「),那麼[]案件,捕捉裏面有什麼:

var r = /\\\[.*?\]|\[(.*?)\]/g; 
     ^^^^^^^^^     MATCH \[this] 
        ^^^^^^^^^  MATCH [this] 

環路與exec讓所有的比賽es:

while(match = r.exec(str)){ 
    console.log(match[1]); 
}