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

查看:33
本文介绍了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?

推荐答案

直接来自 perldoc perlre:

警告 1 vs $1

有些人太习惯写作了诸如:

Some people get too used to writing things like:

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

这是一个 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

或者如果你尝试去做

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天全站免登陆