December 2023
Intermediate to advanced
242 pages
5h 28m
English
| Recipe 32 | Excluding Groups from Result with the Non-capturing Group |
Let’s say you need to keep track of a particular golf player’s ranking based on information scraped from the player’s profile on a sports blog. The ranking information is in a string with an ordinal indicator such as “3rd” or “4th.” You only care about the number, not its suffix, and want to use a capturing group to extract it for additional processing.
If you use /(\d{1,2})(st|nd|rd|th)/, the second parentheses will capture the suffix, too, which is redundant. You need a way to tell the regex engine not to capture those letters.
Add a question mark (?) and a colon (:) right after the opening parentheses to create a non-capturing group:
Read now
Unlock full access