简体   繁体   English

Perl正则表达式替换

[英]Perl regular expression replacement

The code is here. 代码在这里。 My question is since $1 is Fred and this is a replacement, which means replacing fred or barney with Fred , why cannot the answer be like I saw FRED with FRED. 我的问题是,因为$1Fred ,这是一个替代品,这意味着更换fred or barneyFred ,为什么不能回答像I saw FRED with FRED. i have no idea for what's going on here. 我不知道这是怎么回事。 Thank you for your answer! 谢谢您的回答!

$_ = "I saw Barney with Fred.";
s/(fred|barney)/\U$1/gi; # $_ is now "I saw BARNEY with FRED."

Because the capturing group not only captures the string Fred but also Barney . 因为捕获组不仅捕获字符串Fred而且捕获Barney So if the regex engine see Fred , it replaces immediately with Uppercase FRED and if the engine sees Barney, it replaces it with Uppercase Barney. 因此,如果正则表达式引擎看到Fred ,则立即将其替换为大写FRED;如果引擎看到Barney,则将其替换为大写Barney。

$1 refers to "whatever the first capturing group captured". $1表示“无论捕获的第一个捕获组是什么”。 So when (fred|barney) matches fred , that's what $1 contains, but when it matches barney , that is then what $1 contains. 因此,当(fred|barney)匹配fred ,这就是$1包含的内容,但是当它匹配barney ,这就是$1包含的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM