Reputation: 905
I'm trying to extract a value inside Double Square brackets: [[x]]
, whilst ignoring everything else in single square brackets: [y]
.
NOTE: This RegEx is to be used in JavaScript, which as far as I understand doesn't support Looking behind
For example, take these 3 strings
[[32]] [Test] Lorem Ipsum
[[16]] Lorem Ipsum
[[2]] Test [BUG]
I want to extract: 32, 16, 2
This is what I've tried
Test 1:
\[([0-9]+)\]
Will only return the value including the inner square brackets, e.g. [32], [16], [2]. I could then just do another RegEx on the result, but I'd like to know how to do it once.
Test 2:
\[.*?\]]
Will return the value, with the double square brackets, e.g. [[32]], [[16]], [[2]]
Upvotes: 4
Views: 3315
Reputation: 42
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)
Upvotes: 0
Reputation: 4887
Did you try /\[\[([0-9]+)\]\]/
? Assuming of course you only expect digits within the double square brackets.
var exp = /\[\[([0-9]+)\]\]/;
var number = exp.exec("[[293]] Test line")[1]
number
should return '293'
.
Upvotes: 0
Reputation: 1
Another way of doing it with pure regex would be to use lookarounds.
(?<=\[\[)[0-9]+(?=\]\])
Upvotes: -1
Reputation: 381
You can use capturing groups to match substrings within patterns.
In JavaScript (the parentheses define the capturing group here):
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)
Console output: ["1", "3"]
See http://www.regular-expressions.info/refcapture.html for more info on capturing groups.
Upvotes: 1
Reputation: 147413
Given:
var s = '[[32]] [Test] Lorem Ipsum [[16]] Lorem Ipsum [[2]] Test [BUG]';
You can use a look–ahead that matches one or more digits followed by ']]' but doesn't include the ']]' in the match:
s.match(/\d+(?=\]\])/g) // ["32", "16", "2"]
Or, if lookahead isn't available, you can use:
s.match(/\[\[(\d+)\]\]/g).map(function(v){return v.replace(/\[+|\]+/g,'');})
though if map is available then probably look–ahead is too. If the input is multi–line, you may need the m flag also.
Upvotes: 3
Reputation: 25370
How about
\[{2}(\d+)\]{2}
Telling Regex you want {2}
[
then some \d
digits then another {2}
]
Upvotes: 0