简体   繁体   中英

NodeJS RegExp non-capturing groups not working like intended

Given a string "14:00-18:00" I would like to get the starting and ending time from it.

My code looks like this:

var startTime = hourRange.match(/([0-9]{2}\:[0-9]{2})(?:\-)/);
var endTime = hourRange.match(/(?:\-)([0-9]{2}\:[0-9]{2})/);

On something like Regex101 that returns 14:00 and 18:00 respectively. But in Javascript the first one returns ['14:00-', '14:00'] and the second one ['-18:00', '18:00'] .

What am I doing wrong?

I think there might be some confusion regarding the difference between a match and a capture so, to clarify: a regex matches one (and only one, without the g modifier) part of the string. Inside this match, it can capture multiple substring.

Your output is the expected behavior, as the match function returns an array composed as follow:

  • the first element is the entire match.
    ([0-9]{2}:[0-9]{2})- matches 14:00- , so that's what the first item will be.

  • the following items are the capturing groups, in order of apparition of their opening parenthesis inside the regex.
    ([0-9]{2}:[0-9]{2})- captures 14:00 in the first capturing group, so that's what the second item of the array will be.

If you use (\\d{2}:\\d{2})-(\\d{2}:\\d{2}) on 14:00-18:00 the overall match (first item in the resulting array) is the entire string and the actual times are captured in groups 1 and 2. The start time and end time are the second and third elements of the result array.

So in the general sense, if you only care about the values of the capturing groups, you can just throw away the element of index 0 which will always be the overall match.

Hopefully that answers your question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM