在Perl正则表达式中\ 1和$ 1有什么区别? [英] What is the difference between \1 and $1 in a Perl regex?

查看:839
本文介绍了在Perl正则表达式中\ 1和$ 1有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将\ 1与$ 1(如果有)进行比较有什么区别,或者它们在所有情况下都可以互换.

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

示例:

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

它们都给出相同的结果,但是有什么区别吗?

They both give the same result but is there any difference?

推荐答案

直接从

关于\ 1与$ 1的警告

Warning on \1 vs $1

有些人习惯于写作 像这样的东西:

Some people get too used to writing things like:

$pattern =~ s/(\W)/\\\1/g;

这是A的RHS的祖父 替代以免震撼sed 上瘾的人,但这是一个肮脏的习惯 进入.那是因为在PerlThink中, "s///"的右侧是 双引号字符串. "\ 1"在 通常的双引号字符串表示 控制-A. Unix的习惯含义 "\ 1"的表示为"s///". 但是,如果您养成了 这样,您就可以进入 麻烦的话,如果再加上一个"/e" 修饰符.

This is grandfathered for the RHS of a substitute to avoid shocking the sed addicts, but it’s a dirty habit to get into. That’s because in PerlThink, the righthand side of an "s///" is a double- quoted string. "\1" in the usual double-quoted string means a control-A. The customary Unix meaning of "\1" is kludged in for "s///". However, if you get into the habit of doing that, you get yourself into trouble if you then add an "/e" modifier.

s/(\d+)/ \1 + 1 /eg;        # causes warning under -w

或者,如果您尝试这样做

Or if you try to do

s/(\d+)/\1000/;

您不能通过说来消除歧义 "{1} 000",而您可以使用 "$ {1} 000".的操作 插值不应混淆 与匹配的操作 向后引用.

You can’t disambiguate that by saying "{1}000", whereas you can fix it with "${1}000". The operation of interpolation should not be confused with the operation of matching a backreference.

当然,它们的意思是两个不同的 在"s///"左侧的内容.

Certainly they mean two different things on the left side of the "s///".

这篇关于在Perl正则表达式中\ 1和$ 1有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆