Recipe 28 | Matching a Range of Characters with Character Classes |
Task
Suppose you’re tasked with searching scanned documents and filtering applicants aged between 20 and 40. The info you need to extract is preceded with “age:”. So, your regex pattern should match the word “age,” followed by a colon, followed by a space, and followed by a range of numbers between 20 and 40.
With what you’ve learned so far, you could use vertical bars in a pair of parentheses to specify the possible matches, like this:
| /Age: (2(0|1|2|3|4|5|6|7|8|9)|3(0|1|2|3|4|5|6|7|8|9)|40)/ |
But what would you do if you wanted to look for a larger range of numbers? You need a better way of defining the range of characters in regex.
Solution ...
Get Text Processing with JavaScript now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.