2012-06-13 78 views
8

可能重複:
Regular Expression to find a string included between two characters, while EXCLUDING the delimiters正則表達式在方括號內獲取文本

我有一個函數在那裏我得到它放在方括號內,但不是括號內爲文本例如

this is [test] line i [want] text [inside] square [brackets] 

從上面的行我想要的話

測試

括號

我與試圖用/\[(.*?)\]/g這樣做,但我沒有得到滿意的結果,我得到它是括號裏面的話,但也括號不是我想要的

我做搜索一些類似類型的問題對SO,但沒有這些解決方案的工作正常進行我在這裏是一個發現(?<=\[)[^]]+(?=\])這在正則表達式教練,但不與JavaScript。這裏是refrence從那裏我得到這個

這是我做過到目前爲止demo

請幫助

+0

它不是完全重複在不正常的字符方括號它必須處理不同那麼其他字符 – sohaan

回答

22

單前瞻應該在這裏做的伎倆:

a = "this is [test] line i [want] text [inside] square [brackets]" 
words = a.match(/[^[\]]+(?=])/g) 

但在一般情況下,execreplace基於循環導致簡單的代碼:

words = [] 
a.replace(/\[(.+?)\]/g, function($0, $1) { words.push($1) }) 
+0

能前瞻正則表達式不能簡化?/[^ \ [\]] +(= \])/克 – Jules

+0

@Jules:好建議,謝謝。 – georg

5

This fiddle使用RegExp.exec僅輸出有什麼括號內。

var data = "this is [test] line i [want] text [inside] square [brackets]" 
var re= /\[(.*?)\]/g; 
for(m = re.exec(data); m; m = re.exec(data)){ 
    alert(m[1]) 
} 
+0

先生可以請你給我解釋一下什麼是循環和發生在我們能使用underscore.js的_each()函數來遍歷 – sohaan