Lesson 10
Embedding Conditions
A powerful yet infrequently used feature of the regular expression language is the capability to embed conditional processing within an expression. This lesson will explore this topic.
Why Embed Conditions?
(123)456-7890
and 123-456-7890
are both acceptable presentation formats for North American phone numbers. 1234567890
, (123)-456-7890
, and (123-456-7890
all contain the correct number of digits, but are badly formatted. How could you write a regular expression to match only the acceptable formats and not any others?
This is not a trivial problem; consider this obvious solution:
Text
123-456-7890 (123)456-7890 (123)-456-7890 (123-456-7890 1234567890 123 456 7890
RegEx
\(?\d{3}\)?-?\d{3}-\d ...
Get Learning Regular Expressions, First Edition 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.