back references

R

REH

How to a specify a back reference immediately followed by a number without
Perl thinking its part of the back reference?
 
A

Anno Siegel

REH said:
How to a specify a back reference immediately followed by a number without
Perl thinking its part of the back reference?

One way:

$_ = 'aba2';
/(.).\1(?:2)/ and print "ok\n";

There are others...

Anno
 
R

REH

Jim Gibson said:
I am guessing you mean backreferences within a regular expression, such
as the \1 in m/(.)\1/ to match any doubled character. (It would have
been nice to have posted a program demonstrating the problem.)

Surround the backreference in parentheses, either capturing or
non-capturing:

m/(.)(\1)2/
or
m/(.)(?:\1)2/

to match any doubled-character followed by a 2.
I'm sorry for being vague. I mean using backreferences in the replacement
part of a regular expression. I need to have a "\1" immediately followed by
a number, such as "\11" but the last one is not part of the backreference.

Thanks
 
A

Anno Siegel

[proposed solution]
I'm sorry for being vague. I mean using backreferences in the replacement
part of a regular expression. I need to have a "\1" immediately followed by
a number, such as "\11" but the last one is not part of the backreference.

You don't use that kind of backreference in the replacement part, you
use the capturing variables $1, $2, etc. This is simple string
interpolation: "${1}2".

Anno
 
R

REH

Anno Siegel said:
backreference.

You don't use that kind of backreference in the replacement part, you
use the capturing variables $1, $2, etc. This is simple string
interpolation: "${1}2".

Anno

Thank you. That's interesting. I've always used the backslash form and
Perl allowed it. Is there a difference between the two?
 
A

Anno Siegel

REH said:
Thank you. That's interesting. I've always used the backslash form and
Perl allowed it. Is there a difference between the two?

Use \1, etc only inside the regex itself (you don't need that often).
Use $1, etc everywhere else, including the replacement part of s///.
See "perldoc perlre", look for "Warning on" (... \1 vs $1).

Anno.


Anno
 
A

Anno Siegel

REH said:
Thank you. That's interesting. I've always used the backslash form and
Perl allowed it. Is there a difference between the two?

Use \1, etc only inside the regex itself (you don't need that often).
Use $1, etc everywhere else, including the replacement part of s///.
See "perldoc perlre", look for "Warning on" (... \1 vs $1).

Anno
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,043
Latest member
CannalabsCBDReview

Latest Threads

Top