最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Can you retrieve multiple regex matches in JavaScript? - Stack Overflow

programmeradmin3浏览0评论

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})?$/

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

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

Is this possible?

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})?$/

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

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

Is this possible?

Share Improve this question asked Jul 4, 2011 at 11:53 DanDan 7,7446 gold badges35 silver badges51 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 11

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})?$/
发布评论

评论列表(0)

  1. 暂无评论