你能在JavaScript中检索多个正则表达式匹配吗? [英] Can you retrieve multiple regex matches in JavaScript?

查看:122
本文介绍了你能在JavaScript中检索多个正则表达式匹配吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在JavaScript中有以下正则表达式,匹配12:23:34:45和12:23之类的字符串

I have the following regular expression in JavaScript which matches strings like "12:23:34:45" and "12:23"

/^([0-9]{1,2}\:){0,3}([0-9]{0,2})?$/

我遇到的问题是,当我查看匹配数据时,只返回3个匹配项。例如对于12:23:34:45返回的比赛是:

The problem I have is that when I look at the match data there are only ever 3 matches returned. e.g. for 12:23:34:45 the matches returned are:

12:23:34:45
34:
45

ie第一个捕获组仅报告其最后一个值。我希望比赛是:

i.e. the first capturing group only reports its last value. I would like the matches to be:

12:23:34:45
12:
23:
34:
45

这可能吗?

推荐答案

不,这在JavaScript(以及除Perl 6和.NET之外的大多数其他正则表达式)中是不可能的。重复捕获组始终存储匹配的最后一个值。只有.NET和Perl允许您单独访问这些匹配项(例如,在.NET中 match.Groups(i).Captures )。

No, this is not possible in JavaScript (and most other regex flavors except Perl 6 and .NET). Repeated capturing groups always store the last value that was matched. Only .NET and Perl allow you to access those matches individually (match.Groups(i).Captures in .NET, for example).

你需要两次传递,第一次是找到字符串,第二次是迭代匹配并扫描它们的子值。

You need two passes, the first to find the strings, the second to iterate over the matches and scan those for their sub-values.

或者使正则表达式明确:

Or make the regex explicit:

/^([0-9]{1,2}:)?([0-9]{1,2}:)?([0-9]{1,2}:)?([0-9]{0,2})?$/

这篇关于你能在JavaScript中检索多个正则表达式匹配吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆