What Is a Regex?
A regex is a sequence of characters that form a pattern that's used to search. Each character in the pattern either has special meaning (a metacharacter) or is meant to match the character itself (a literal). This is perhaps best understood by the following example.
As a demonstration of the difference between pattern matching with conventional coding versus regex techniques, consider the following code for matching phone number format patterns in a conventional way. We'll then rewrite the matching logic using a regex for comparison. To keep things simple, we will only look for phone numbers that match the following pattern, which is common for phone numbers, particularly in the United States:
[2-9]XX-XXX-XXXX
Here, X
can be any digit from 0-9
, and the first digit cannot be a zero or one (only 2-9
are permitted). For example, 234-567-8901
is a valid phone number in this format.
You can use the following code to do the matching using conventional...