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.
|Regex options: None|
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 ‹
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
escapes are much easier to understand.
When the regular expression ‹
2008-08-08, the first
20. The regex
engine then enters the capturing group, noting the position reached in
the subject text.
the capturing group matches
08, and the engine reaches the group’s closing parenthesis. At ...