How do I match a number inside square brackets with regex

前端 未结 4 1128
情书的邮戳
情书的邮戳 2020-12-16 16:49

I wrote a regular expression which I expect should work but it doesn\'t.

  var regex = new RegExp(\'(?<=\\[)[0-9]+(?=\\])\')

Javascript

相关标签:
4条回答
  • 2020-12-16 16:51

    To increment multiple numbers in the form of lets say:

    var str = '/a/b/[123]/c/[4567]/[2]/69';
    

    Try:

    str.replace(/\[(\d+)\]/g, function(m, p1){
     return '['+(p1*1+1)+']' }
    )
    
    //Gives you => '/a/b/[124]/c/[4568]/[3]/69'
    
    0 讨论(0)
  • 2020-12-16 16:52

    Lookahead is supported, but not lookbehind. You can get close, with a bit of trickery.

    0 讨论(0)
  • 2020-12-16 17:06

    If you're quoting a RegExp, watch out for double escaping your backslashes.

    0 讨论(0)
  • 2020-12-16 17:15

    This should work:

    var regex = /\[[0-9]+\]/;
    


    edit: with a grouping operator to target just the number:

    var regex = /\[([0-9]+)\]/;
    

    With this expression, you could do something like this:

    var matches = someStringVar.match(regex);
    if (null != matches) {
      var num = matches[1];
    }
    
    0 讨论(0)
提交回复
热议问题