Serge314 has asked for the wisdom of the Perl Monks concerning the following question:

Hello,

How we can separate a backreference from a digit?

print "Match1\n" if "aa1" =~ /^(a)\1(#)1$/; # comment not works print "Match2\n" if "aa1" =~ /^(a)\1.{0}1$/; # works, but it's very ug +ly print "Match3\n" if "aa1" =~ /^(a)\1 1$/x; # works, but I don't want + to use x modifier... print "Match4\n" if "aa1" =~ /^(a)\g{1}1$/; # works, but since Perl 5 +.10...

Regards
Serge

Replies are listed 'Best First'.
Re: How we can separate a backref from a digit?
by ikegami (Patriarch) on Mar 18, 2011 at 07:17 UTC
    Using (?:\1) works.
      It looks good. By the way:
      $a=1; print "Match\n" if "aa1" =~ /^(a)\1$a$/; # not match!
      After interpolation of variables we get the false backlink \11! To all: should I submit a bug report to perl.org?
      Serge
        Not a bug.
Re: How we can separate a backref from a digit?
by BrowserUk (Patriarch) on Mar 18, 2011 at 07:30 UTC

    A few more ways, I think the last would be my choice

    print "Match1\n" if "aa1" =~ /^(a)\1()1$/;; Match1 print "Match1\n" if "aa1" =~ /^(a)\1(?:)1$/;; Match1 print "Match1\n" if "aa1" =~ /^(a)\1(?:1)$/;; Match1 print "Match1\n" if "aa1" =~ /^(a)\1+1$/;; Match1 print "Match1\n" if "aa1" =~ /^(a)\1{1}1$/;; Match1

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: How we can separate a backref from a digit?
by JavaFan (Canon) on Mar 18, 2011 at 10:02 UTC
    The problems you mention are exactly why 5.10 has \g{}.

    Pre-5.10, you'll have to use an ugly fix. And it can even be worse:

    /....\11..../
    Backref to the 11th set of parenthesis, or a tab?
Re: How we can separate a backref from a digit?
by Anonymous Monk on Mar 18, 2011 at 07:14 UTC