Lesson 3: Matching Digits in Regular Expressions
The \d
metacharacter is a cornerstone in regex to identify digits in a string. Standing for "digit", it matches any single numeral from 0 to 9, providing a clean and straightforward way to locate numerical data. For example, \d
will match any single digit in a string such as the '3' in abc3def
.
Combining \d with Quantifiers
To extend its functionality, \d
can be used with quantifiers to match specific numbers of consecutive digits. For example, \d{3}
would match any sequence of three digits, like 123
in a123b
. Meanwhile, \d+
will match one or more digits, like 4567
in abc4567def
.
Negating \d: Matching Non-digits
Sometimes, you might want to match non-digit characters, and for such purposes, the negation of \d
, i.e., \D
comes into play. \D
will match any character that is not a digit, enhancing your matching capability to non-numerical data.
Exercise 3: Mastering the \d Metacharacter
Now that you have a grasp on the \d
metacharacter, it's time to put your knowledge into practice. You're tasked with verifying the formats of product IDs in an inventory system. A valid product ID consists of a prefix "PID-", followed by 5 digits. Create a regex pattern to match and validate such product IDs.