December 2023
Intermediate to advanced
242 pages
5h 28m
English
| Recipe 33 | Reading Groups with Ease Using Named Capturing Groups |
Suppose you need to find the exact time when an error occurred by searching through a log file. You know that the time is in the format of hours, minutes, seconds, and AM/PM indicator (HH:MM:SS XM). To extract each time segment, you create a pattern that can recognize and capture each segment separately. However, as the number of groups in the pattern increases, the already cryptic regex syntax becomes even harder to read. Consider this example:
| | const re = /(\d{2}):(\d{2}):(\d{2})\s(\w{2})/; |
| | const match = "09:30:00 AM".match(re); |
| | |
| | console.log(match[1]); |
| | console.log(match[2]); |
| | console.log(match[3]); |
| | console.log(match[4]); ... |
Read now
Unlock full access