Regular expression to get number between two square brackets

前端 未结 6 1676
死守一世寂寞
死守一世寂寞 2021-01-27 14:19

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 tr

相关标签:
6条回答
  • 2021-01-27 14:22

    You can capture the digits using groups

    "[12]],23,asd".match(/\[\[(\d+)\]\]/)[1]
    => "12"
    
    0 讨论(0)
  • 2021-01-27 14:24

    You can use the following regex,

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

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

    It uses capture groups concept

    0 讨论(0)
  • 2021-01-27 14:27

    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);
    
    0 讨论(0)
  • 2021-01-27 14:32
    \[\[(\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.
    }
    
    0 讨论(0)
  • 2021-01-27 14:43

    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
    
    0 讨论(0)
  • 2021-01-27 14:45

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

    \[\[(\d+)\]\]\S+\[\[(\d+)\]\]
    
    0 讨论(0)
提交回复
热议问题