December 2023
Intermediate to advanced
242 pages
5h 28m
English
| Recipe 30 | Treating Multiple Characters as a Single Unit with the Capturing Group |
Suppose you want to search an archive of documents and retrieve those that mention a date in August. The only clue you have is that the date comes in four different styles. For example: “August 16,” “August 16th,” “Aug 16,” or “Aug 16th.”
To match such a date with regex, you need a way to make “ust” in “August” and “th” in “16th” optional.
To make certain letters optional, group them by enclosing them in parentheses and place a question mark after the group:
| | const re = /\bAug(ust)?\s\d{1,2}(st|nd|rd|th)?\b/; |
| | |
| | // Grouping allows matching many alternatives |
| | re.test("Aug 16" |
Read now
Unlock full access