Skip to Content
Regular Expressions Cookbook
book

Regular Expressions Cookbook

by Jan Goyvaerts, Steven Levithan
May 2009
Intermediate to advanced
510 pages
15h
English
O'Reilly Media, Inc.
Content preview from Regular Expressions Cookbook

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Regular Expressions Cookbook, 2nd Edition

Regular Expressions Cookbook, 2nd Edition

Jan Goyvaerts, Steven Levithan

Publisher Resources

ISBN: 9780596802837Catalog PageErrata