簡體   English   中英

正則表達式:獲取%符號之間的字符串(不包括符號)

[英]RegEx: Get a string between % signs excluding the signs

例如,在字符串中

'apple %cherry% carrots %berries2%'

我想提取以下內容:

[
 'cherry',
 'berries2'
]

我已經嘗試使用以下RegEx,但它們都包含%符號:

/%[a-zA-Z\d]+%/g

我根據在這里找到的RegEx制作了此RegEx: Regex以匹配%之間的字符串

如果情況有所不同,這是我提取字符串的方法: 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"]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM