【问题标题】:Firefox Javascript regex to get array of numbers within square brackets but excluding bracketsFirefox Javascript 正则表达式获取方括号内的数字数组,但不包括括号
【发布时间】:2019-08-25 01:25:17
【问题描述】:

示例输入

var abc = "blah blah [abc] , [123] [ab12], [456] [cdef] 789 ghi000 "

预期输出

["123", "456"]

我正在尝试编写只匹配方括号内的数字并返回这些数字的数组(不包括 [])的正则表达式。

我尝试使用的正则表达式使用lookbehind,因此它在 Chrome 中有效,但在 firefox 中失败。后来发现firefox还不支持lookbehind(访问https://bugzilla.mozilla.org/show_bug.cgi?id=1225665)。

abc.match(/(?<=\[)(\d+)/g);

我在 Chrome 76 上得到了预期的输出:

["123", "456"]

但我在 Firefox 68 上遇到错误:

SyntaxError: invalid regexp group

如何编写适用于两者并生成预期结果的正则表达式。

【问题讨论】:

    标签: javascript regex firefox lookbehind


    【解决方案1】:

    您可以使用matchmap

    var abc = "blah blah [abc] , [123] [ab12], [456] [cdef] 789 ghi000 "
    
    let output = abc.match(/\[\d+\]/g).map(m=>m.replace(/\[(\d+)\]/g, "$1"))
    
    console.log(output)

    或者你可以使用exec

    var regex1 = /\[(\d+)\]/g
    var str1 = "blah blah [abc] , [123] [ab12], [456] [cdef] 789 ghi000 "
    var array1;
    
    while ((array1 = regex1.exec(str1)) !== null) {
      console.log(`Found ${array1[1]}`);
    }

    【讨论】:

      【解决方案2】:

      使用捕获组,例如:

      var abc = "blah blah [abc] , [123] [ab12], [456] [cdef] 789 ghi000 ";
      Array.from(abc.matchAll(/\[(\d+)\]/g)).map(m => m[1])
      

      matchAll (注意浏览器兼容性) 查找[NNN] 的每一个匹配项,并将方括号内的数字捕获为match[1]

      Array.from() 将从matchAll 返回的迭代器转换为数组,然后可以对其进行处理以提取捕获。

      【讨论】:

      • 感谢您的解决方案,它确实有效,但是由于浏览器兼容性(正如您也提到的),我现在将避免使用 matchAll。
      • 当然,这不会改变使用捕获组的主要思想。你只需要在一个循环中 use RegExp's exec 而不是我的单行。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-30
      • 1970-01-01
      • 2013-06-17
      • 1970-01-01
      相关资源
      最近更新 更多