javascript - match 函数返回一个包含两个元素而不是一个元素的数组

标签 javascript regex match

我有这样一行:

\/Date(1475832958000)\/

我想从中提取一个数字。我这样做了:

var regex = /(\d+)/;
var str = '\/Date(1475832958000)\/';
console.log(str.match(regex));
//["1475832958000", "1475832958000"]

我得到一个包含 2 个元素的数组。我不懂为什么。请帮忙。

最佳答案

在正则表达式 () is using for capturing group 中,第一个元素是完全匹配,第二个元素是捕获的值。

来自MDN docs :

An Array containing the entire match result and any parentheses-captured matched results; null if there were no matches.

<小时/>

如果您只想获取括号内的数字,请转义括号(通过添加反斜杠,\)。

var regex = /\(\d+\)/;
var str = '\/Date(1475832958000)\/';
console.log(str.match(regex));

// or in case you just want to get the number 
// then use capturing group
var regex1 = /\((\d+)\)/;
console.log(str.match(regex1));

关于javascript - match 函数返回一个包含两个元素而不是一个元素的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43889319/

相关文章:

javascript 正则表达式 trim 到 'space' AND 'dash' 或匹配

asp.net - 在哪里插入脚本 block

javascript - 删除javascript字符串前后的多余空格

javascript - 如何在 jQuery 中停止 onChange 事件

javascript - 正则表达式 Javascript 数字逗号分隔 | > | >= <=

正则表达式以字符串开头和/或结尾 - 如何简化?

excel - 在 INDEX(MATCH(COUNTIF())) 公式中处理标准字符处的通配符

javascript - 函数检查字符串并更改它们

regex - 如何制作可移植正则表达式?

google-sheets - 嵌套公式无法按预期运行 Google 表格