2017-04-23 33 views
2

正在處理像[enclosed str]outer str[enclosed str] 這樣的字符串格式,並且正試圖匹配所有[enclosed str]匹配直到字符的非轉義版本

問題是我想除了非轉義版本的](即]之前沒有加上\)之外的任何字符在方括號內。

例如

str = 'string[[enclosed1\\]]string[enclosed2]'; 

// match all [ followed by anything other ] then a ] 
str.match(/\[[^\]]+]/g) 
// returns ["[[enclosed1\]", "[enclosed2]"] 
// ignores the `]` after `\\]` 

// match word and non-word char enclosed by [] 
str.match(/\[[\w\W]+]/g) 
// returns ["[[enclosed1\]]string[enclosed2]"] 
// matches to the last ] 
// making it less greedy with /\[[\w\W]+?]/g 
// returns same result as /\[[^\]]+]/g 

是它的JavaScript正則表達式中可以達到我想要的結果是

["[[enclosed1\]]", "[enclosed2]"] 
+1

我的問題是你設置的正則表達式模式,以「先進的專業」。而且還沒有達到那個水平呢! – twist

+0

如何使用['/\[+[^\[]+\]/g'](https://regex101.com/r/i1REKm/2);)。 –

回答

1

用正則表達式在JavaScript中不支持負回顧後,這是我能想出的最好的與:

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

組1將包含您想要的字符串。

https://regex101.com/r/PmDcGH/3

相關問題