tarzanbappa
tarzanbappa

Reputation: 4958

Regular expression to get number between two square brackets

Hi I need to get a string inside 2 pair of square brackets in javascript using regular expressions.

here is my string [[12]],23,asd

So far what I tried is using this pattern '\[\[[\d]+\]\]'

and I need to get the value 12 using regular expressions

Upvotes: 0

Views: 400

Answers (6)

Evgeniy
Evgeniy

Reputation: 2921

I've only done it with 2 regExps, haven't found the way to do it with one:

var matches = '[[12]],23,asd'.match(/\[{2}(\d+)\]{2}/ig),
    intStr = matches[0].match(/\d+/ig);

console.log(intStr);

Upvotes: 0

LumberHack
LumberHack

Reputation: 850

Here is a regex you can use, capture groups to get $1 and $2 which will be 12 and 43 respectively

\[\[(\d+)\]\]\S+\[\[(\d+)\]\]

Upvotes: 1

Srinath Mandava
Srinath Mandava

Reputation: 3462

If you need to get 12 you can just use what you mentioned with a capturing group \[\[(\d+)\]\]

var myRegexp= /\[\[(\d+)\]\]/;
var myString='[[12]],23,asd';
var match = myRegexp.exec(myString);
console.log(match[1]); // will have 12

Upvotes: 0

nu11p01n73R
nu11p01n73R

Reputation: 26667

You can capture the digits using groups

"[12]],23,asd".match(/\[\[(\d+)\]\]/)[1]
=> "12"

Upvotes: 1

apgp88
apgp88

Reputation: 985

You can use the following regex,

\[\[(\d+)\]\]

This will extract 12 from [[12]],23,asd

It uses capture groups concept

Upvotes: 2

vks
vks

Reputation: 67968

\[\[(\d+)\]\]

Try this.Grab the capture or group 1.See demo.

var re = /\[\[(\d+)\]\]/gs;
var str = '[[12]],23,asd';
var m;

while ((m = re.exec(str)) != null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}

Upvotes: 1

Related Questions