2014-01-21 112 views

回答

4

試試這個正則表達式:

/[a-zA-Z\d]+(?=%)/g 

(?= ...)是一個積極的向前看,這基本上意味着它會檢查,以確保內容在字符串中,而沒有實際捕獲它們。

不需要第一個%,因爲%不符合[a-zA-Z\d]

試運行:

var matches = 'apple %cherry% carrots %berries2%'.match(/[a-zA-Z\d]+(?=%)/g); 
console.log(matches); // => ["cherry", "berries2"] 
+1

但它可能會導致問題,如果字符串有一個'蘋果'%爲好。 – anubhava

+0

它的工作,謝謝澄清:) – Pixy

3

這應該工作:

var re = /%([^%]*)%/g, 
    matches = [], 
    input = 'apple %cherry% carrots %berries2%'; 
while (match = re.exec(input)) matches.push(match[1]); 

console.log(matches); 
["cherry", "berries2"] 
相關問題