Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

(SOLVED) RegEx: backreferences in character classes

by LanX (Sage)
on Oct 24, 2021 at 10:50 UTC ( #11137959=perlquestion: print w/replies, xml ) Need Help??

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

Hi

I'm failing to use relative backreferences in \g-form in character classes.

Please note how [^\1] still works, but [^\g-1] fails.

Is there a better syntax within character classes?

I'm afraid I need to switch to negated look-aheads or hardcode different quotes.

Debugger demo with perl-de0

The following regex tries to match quoted substrings in $1, the quote in $2

DB<164> p $_ __'abc'__"def"__ DB<165> x / ( (['"]) [^\2]*? \2 ) /gx # OK 0 '\'abc\'' 1 '\'' 2 '"def"' 3 '"' DB<166> x / ( (['"]) [^\2]*? \g-1 ) /gx # OK 0 '\'abc\'' 1 '\'' 2 '"def"' 3 '"' DB<167> x / ( (['"]) [^\g-1]*? \g-1 ) /gx # OOPS Invalid [] range "\g-1" in regex; marked by <-- HERE in m/ ( (['"]) [^ +\g-1 <-- HERE ]*? \g-1 ) / at (eval 179)[c:/St\ rawberry/perl/lib/perl5db.pl:738] line 2. at (eval 179)[c:/Strawberry/perl/lib/perl5db.pl:738] line 2. eval 'no strict; ($@, $!, $^E, $,, $/, $\\, $^W) = @DB::saved; +package main; $^D = $^D | $DB::db_stop; / ( ([\'"]) [^\\g-1]*? \\g-1 ) /gx; ' called at c:/Strawberry/perl/lib/perl5db.pl line 738 DB::eval called at c:/Strawberry/perl/lib/perl5db.pl line 3138 DB::DB called at -e line 1 DB<168> p $] 5.032001 DB<169>

FWIW: \g{-1} instead of \g-1 doesn't help either

This question is a follow-up to solution wanted for break-on-spaces (w/specifics)

Cheers Rolf
(addicted to the Perl Programming Language :)
Wikisyntax for the Monastery

update

) or using (??{..})

SOLUTION

escaping the dash inside character classes helps, otherwise it's seen as a range

DB<170> x / ( (['"]) [^\g\-1]*? \g-1 ) /gx 0 '\'abc\'' 1 '\'' 2 '"def"' 3 '"' DB<171> x / ( (['"]) [^\g{\-1}]*? \g-1 ) /gx 0 '\'abc\'' 1 '\'' 2 '"def"' 3 '"' DB<172> x / ( (['"]) [^\g2]*? \g-1 ) /gx 0 '\'abc\'' 1 '\'' 2 '"def"' 3 '"' DB<173>

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://11137959]
Approved by Athanasius
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (7)
As of 2021-12-02 15:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    R or B?



    Results (22 votes). Check out past polls.

    Notices?