Regular Expressions Cookbook, 2nd Edition
by Steven Levithan
Published by
O'Reilly Media, Inc., 2012
and
Tags
| Regex options: None |
| Regex flavors: .NET, Java 7, XRegExp, PCRE 7, Perl 5.10, Ruby 1.9 |
\b(?'area'\d{3})(?'exchange'\d{3})(?'number'\d{4})\b| Regex options: None |
| Regex flavors: .NET, PCRE 7, Perl 5.10, Ruby 1.9 |
\b(?P<area>\d{3})(?P<exchange>\d{3})(?P<number>\d{4})\b| Regex options: None |
| Regex flavors: PCRE, Perl 5.10, Python |
(${area})●${exchange}-${number}| Replacement text flavors: .NET, Java 7, XRegExp |
(\g<area>)●\g<exchange>-\g<number>| Replacement text flavor: Python |
(\k<area>)●\k<exchange>-\k<number>| Replacement text flavor: Ruby 1.9 |
(\k'area')●\k'exchange'-\k'number'| Replacement text flavor: Ruby 1.9 |
($+{area})●$+{exchange}-$+{number}| Replacement text flavor: Perl 5.10 |
($1)●$2-$3| Replacement text flavor: PHP |
.NET, Java 7, XRegExp, Python, and Ruby 1.9 allow you to use named backreferences in the replacement text if you used named capturing groups in your regular expression. The syntax for named backreferences in the replacement text differs from that in the regular expression.
Ruby uses the same syntax for backreferences in the replacement
text as it does in the regular
expression. For named capturing groups in Ruby 1.9, this syntax is
«\k<group>» or «\k'group'». The choice
between angle brackets and single quotes is merely a notational
convenience.
Perl 5.10 and later store the text matched by named capturing
groups into the hash %+. You can
get the text matched by the group “name” with $+{name}. Perl interpolates variables in the
replacement text, so you can treat «$+{name}» as a named backreference in
the replacement text.
PHP (using PCRE) supports named capturing groups in regular expressions, but not in the replacement text. You can use numbered backreferences in the replacement text to named capturing groups in the regular expression. PCRE assigns numbers to both named and unnamed groups, from left to right.
.NET, Java 7, XRegExp, Python, and Ruby 1.9 also allow numbered references to named groups. However, .NET uses a different numbering scheme for named groups, as Recipe 2.11 explains. Mixing names and numbers with .NET, Java 7, XRegExp, Python, or Ruby is not recommended. Either give all your capturing groups names or don’t name any groups at all. Always use named backreferences for named groups.
Recipe 2.9 explains the capturing groups that backreferences refer to.
Recipe 2.11 explains named capturing groups. Naming the groups in your regex and the backreferences in your replacement text makes them easier to read and maintain.
Search and Replace with Regular Expressions in Chapter 1 describes the various replacement text flavors.
Recipe 2.10 shows how to use backrefreences in the regular expression itself. The syntax is different than for backreferences in the replacement text.
Recipe 3.15 explains how to use replacement text in source code.