Can you retrieve multiple regex matches in JavaScript?

前端 未结 1 1378
慢半拍i
慢半拍i 2020-12-04 02:02

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


        
相关标签:
1条回答
  • 2020-12-04 02:29

    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 讨论(0)
提交回复
热议问题