[英]RegEx - Value inside double square brackets
我試圖在Double Square括號中提取一個值: [[x]]
,而忽略單個方括號中的所有其他內容: [y]
。
注意: 此RegEx將在JavaScript中使用,據我所知,它不支持后視
例如,取這3個字符串
[[32]] [Test] Lorem Ipsum
[[16]] Lorem Ipsum
[[2]] Test [BUG]
我想提取: 32,16,2
這就是我嘗試過的
測試1:
\\[([0-9]+)\\]
只會返回包含內方括號的值,例如[32],[16],[2] 。 然后我可以在結果上再做一次RegEx,但我想知道如何做一次。
測試2:
\\[.*?\\]]
將使用雙方括號返回值,例如[[32]],[[16]],[[2]]
鑒於:
var s = '[[32]] [Test] Lorem Ipsum [[16]] Lorem Ipsum [[2]] Test [BUG]';
您可以使用匹配一個或多個數字后跟']]'但在匹配中不包含']]'的預測:
s.match(/\d+(?=\]\])/g) // ["32", "16", "2"]
或者,如果沒有預測,您可以使用:
s.match(/\[\[(\d+)\]\]/g).map(function(v){return v.replace(/\[+|\]+/g,'');})
雖然如果地圖可用,那么可能也是前瞻性的。 如果輸入是多行的,您可能還需要m標志。
您可以使用捕獲組來匹配模式中的子字符串。
在JavaScript中(括號在此定義捕獲組):
var pattern = /\[\[([0-9]+)\]\]/g;
var string = "[[1]] [2] [[3]] [4] [[five]]";
var numbers = [];
while (match = pattern.exec(string)) {
numbers.push(match[1]); //Get capturing group 1. This would be e.g. "1"
// NOTE: match[0] contains the entire match. e.g. "[[1]]"
}
console.log(numbers)
控制台輸出: ["1", "3"]
有關捕獲組的更多信息,請參見http://www.regular-expressions.info/refcapture.html 。
你試過/\\[\\[([0-9]+)\\]\\]/
? 當然假設您只希望雙方括號內的數字。
var exp = /\[\[([0-9]+)\]\]/;
var number = exp.exec("[[293]] Test line")[1]
number
應返回'293'
。
怎么樣
\[{2}(\d+)\]{2}
告訴正則表達式你想要{2}
[
然后一些\\d
數字然后另一個{2}
]
let str = 'test [[1]], test [[2]], xyz, abc, <p>Hi</p> test [[3]].'
let result = str.match(/\[\[(\d+)\]\]/g).map((item) => {
return parseInt(item.replace(/[\[\]]/g, ''))
})
console.log(result)
使用純正則表達式的另一種方法是使用外觀。
(?<=\[\[)[0-9]+(?=\]\])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.