Match any contiguous sequence of 10 digits, such as
1234567890. Convert the
sequence into a nicely formatted phone number, for example,
|Regex options: None|
|Replacement text flavors: .NET, PHP, Perl|
|Replacement text flavors: PHP, Python, Ruby|
Recipe 2.10 explains how you can use capturing groups in your regular expression to match the same text more than once. The text matched by each capturing group in your regex is also available after each successful match. You can insert the text of some or all capturing groups—in any order, or even more than once—into the replacement text.
Some flavors, such as Python and Ruby, use the same «
\1» syntax for
backreferences in both the regular expression and the replacement
text. Other flavors use Perl’s «
$1» syntax, using a dollar sign
instead of a backslash. PHP supports both.
In Perl, «
$1» and above are actually variables
that are set after each successful regex match. You can use them
anywhere in your code until the next regex match. .NET, Java,
$1» only in the replacement syntax.
These programming languages do offer other ways to access capturing
groups in code. Chapter 3 ...