|
Posted by Toby Inkster on 01/28/07 10:34
Jonathan N. Little wrote:
> Takes the "stuff" matching in the first part with the "()" and puts it
> in the second part at the "\1", but I think in Perl "$1" is preferred
Some regexp engines use $1, others use \1. My text editor uses the
backslash syntax.
Perl supports both, but treats them slightly differently. For example:
#!/usr/bin/perl
print "Type a sentance> ";
$_ = <>; # Read a line.
s/^(.+)\s+(.*)/$2 $1/; # Swap around first 2 words.
s/^(.+)\s+(.*)/\2 \1/; # Swap them back.
if (/^(.+)\s+/) # If the sentance starts with a word
{ $first = $1; } # Put it in $first.
if (/^(.+)\s+/) # Try this again...
{ $first = \1; } # Doesn't do what you expect!
That is, $-style backreferences become available to the rest of your
program until they get overwritten; \-style ones are only available
within the original regular expression.
PHP allows \1 and $1 and also, in line with PHP's string interpolation
synatx, ${1} and {$1}. They are all treated as equivalent, but the
curly braces ones are useful for distinguishing between ambiguous
cases. For example: '${12}' versus '${1}2; the former is backreference
twelve followed by nothing; the latter is backreference one followed by
the literal string '2'.
sed uses \1 to \9. The $-syntax is not recognised, and backreferences \10
and higher are not supported.
--
Toby A Inkster BSc (Hons) ARCS
Contact Me ~ http://tobyinkster.co.uk/contact
Navigation:
[Reply to this message]
|