'apple %cherry% carrots %berries2%'
我想提取以下中:
[
'cherry',
'berries2'
]
我試着用下面的正則表達式,但它們都包含%招牌:
/%[a-zA-Z\d]+%/g
我根據我發現這裏的那些做這個表達式:Regex to match string between %
如果有差別,這裏就是我提取字符串:http://jsfiddle.net/pixy011/APab8/
'apple %cherry% carrots %berries2%'
我想提取以下中:
[
'cherry',
'berries2'
]
我試着用下面的正則表達式,但它們都包含%招牌:
/%[a-zA-Z\d]+%/g
我根據我發現這裏的那些做這個表達式:Regex to match string between %
如果有差別,這裏就是我提取字符串:http://jsfiddle.net/pixy011/APab8/
試試這個正則表達式:
/[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"]
這應該工作:
var re = /%([^%]*)%/g,
matches = [],
input = 'apple %cherry% carrots %berries2%';
while (match = re.exec(input)) matches.push(match[1]);
console.log(matches);
["cherry", "berries2"]
但它可能會導致問題,如果字符串有一個'蘋果'%爲好。 – anubhava
它的工作,謝謝澄清:) – Pixy