使整个匹配在RegEx中不捕获

时间:2019-03-11 14:40:36

标签: javascript regex

我有如下正则表达式:

const regex = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;

const result = "1988-02-01 12:12:12".match(regex);

console.log(result)

在这里,结果是将第一个项目作为一个整体匹配,是否有可能从结果中排除整个匹配?目前,我最终对结果进行了shift()的查询,只是想知道是否可以将整个比赛标记为不吸引人。

3 个答案:

答案 0 :(得分:3)

您可以使用解构使用[,...result]从结果数组中分离出第一个值:

const regex = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;

const [,...result] = "1988-02-01 12:12:12".match(regex);

console.log(result)

如果您知道输入格式可以,那么您可以执行以下操作:

result = "1988-02-01 12:12:12".match(/\d+/g)

const regex = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;

const result = "1988-02-01 12:12:12".match(/\d+/g);

console.log(result)

或者进行更多检查:.match(/(^\d{4}|\b\d{2})\b/g)

const regex = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;

const result = "1988-02-01 12:12:12".match(/(^\d{4}|\b\d{2})\b/g);

console.log(result)

此外,如果您希望具有与数字数据类型等效的数组,则使用Number作为回调函数进行映射:

const regex = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;

const [,...result] = ("1988-02-01 12:12:12".match(regex)||[]).map(Number);

console.log(result)

附加的||[]处理模式不匹配的情况,并用空数组交换null

答案 1 :(得分:2)

您可以看看named groups

ID  A   B   C   X
1   A1  B3  C1  1
2   A1  B2  C5  1
3   A1  B10 C10 1
4   A2  B1  C5  1
5   A2  B8  C1  1
6   A3  B1  C4  1
7   A4  B6  C3  1
8   A4  B3  C5  1
9   A5  B7  C2  2
10  A6  B10 C3  1
11  A8  B5  C4  1

答案 2 :(得分:0)

我同意Trincot并使用解构方法。根据Mozilla的文档,完全匹配进入第一个索引是设计使然: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec

对象:结果

属性/索引:[0]

说明:匹配的完整字符串