2.10. Match Previously Matched Text Again
Problem
Create a regular expression that matches “magical” dates in yyyy-mm-dd format. A date is magical if the year minus the century, the month, and the day of the month are all the same numbers. For example, 2008-08-08 is a magical date. You can assume all dates in the subject text to be valid. The regular expression does not have to exclude things like 9999-99-99, as these won’t occur in the subject text. You only need to find the magical dates.
Solution
\b\d\d(\d\d)-\1-\1\b
Regex options: None |
Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby |
Discussion
To match previously matched text later in a regex, we
first have to capture the previous text. We do that with a capturing
group, as shown in Recipe 2.9. After that, we can
match the same text anywhere in the regex using a backreference. You can reference
the first nine capturing groups with a backslash followed by a single
digit one through nine. For groups 10 through 99, use ‹\10
› to ‹\99
›.
Warning
Do not use ‹\01
›.
That is either an octal escape or an error. We don’t use octal escapes
in this book at all, because the ‹\xFF
› hexadecimal escapes are much easier to
understand.
When the regular expression ‹\b\d\d(\d\d)-\1-\1\b
› encounters 2008-08-08
, the first
‹\d\d
› matches 20
. The regex engine then
enters the capturing group, noting the position reached in the subject
text.
The ‹\d\d
› inside
the capturing group matches 08
, and the engine reaches the group’s closing parenthesis. At ...
Get Regular Expressions Cookbook, 2nd 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.