简体   繁体   English

Firefox Javascript正则表达式获取方括号内但不包括方括号的数字数组

[英]Firefox Javascript regex to get array of numbers within square brackets but excluding brackets

Sample input 样本输入

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

Expected output 预期产量

["123", "456"]

I am trying to write regex that should match only the numbers within the square brackets and return an array of those numbers (excluding the []). 我正在尝试编写只与方括号内的数字匹配的正则表达式,并返回这些数字的数组(不包括[])。

The regex that I tried used lookbehind so it worked from Chrome but failed for firefox. 我尝试过的正则表达式使用了backbehind,因此它可以在Chrome浏览器上运行,但无法使用Firefox。 I found later that lookbehind is not yet supported in firefox (Visit https://bugzilla.mozilla.org/show_bug.cgi?id=1225665 ). 后来我发现firefox还不支持lookbehind(访问https://bugzilla.mozilla.org/show_bug.cgi?id=1225665 )。

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

I get the expected output on Chrome 76: 我在Chrome 76上获得了预期的输出:

["123", "456"]

but I get error on Firefox 68: 但在Firefox 68上出现错误:

SyntaxError: invalid regexp group

How can I write a regex that works on both and generate expected result. 我该如何编写同时适用于两者的正则表达式并生成预期结果。

You can use match and map 您可以使用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) 

Or you can use exec 或者您可以使用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]}`); } 

Use capturing groups, eg: 使用捕获组,例如:

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

matchAll (note the browser compatibility) finds every occurrence of [NNN] and captures the digits inside the square brackets as match[1] . matchAll (注意浏览器的兼容性)查找每次出现的[NNN]并将方括号内的数字捕获为match[1]

Array.from() converts the iterator returned from matchAll to an array, which can then be processed to extract the capture. Array.from()matchAll返回的迭代器转换为数组,然后可以对其进行处理以提取捕获。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM