Regular expression to get number between two square brackets

陌路散爱 提交于 2021-02-05 11:49:35

问题


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


回答1:


You can capture the digits using groups

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



回答2:


You can use the following regex,

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

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

It uses capture groups concept




回答3:


\[\[(\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.
}



回答4:


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

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



回答5:


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



回答6:


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);


来源:https://stackoverflow.com/questions/29160705/regular-expression-to-get-number-between-two-square-brackets

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!