What is the difference between \1 and $1 in a Perl regex?

后端 未结 3 1165
死守一世寂寞
死守一世寂寞 2020-12-01 17:19

What is the difference of doing \\1 as opposed to $1 if any, or are they interchangeable in all situations.

Example:

s/([a-z]+),afklol/$1,bck/;
#agai         


        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-01 17:44

    I only use \1 on the rare occasions where I need the match to include a repeat of an earlier part of the pattern. e.g.

    /(foo|bar)baz\1/
    

    This would match "foobazfoo" or "barbazbar" but not "foobazbar". You can't use $1 there.

    In all other circumstances I use $1 and kin, because there are too many gotchas to using the other notation. See perlre for all the gory details.

提交回复
热议问题