如何在正则表达式中使用 Perl 变量? [英] How do I use a Perl variable in a regular expression?

查看:41
本文介绍了如何在正则表达式中使用 Perl 变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试进行搜索并替换为变量.在这种情况下,我从上一场比赛中提取的变量.这是我的代码:

I am trying to do a search and replace with variables. In this case variables that I pulled from a previous match. Here is my code:

$fileContentToAlter =~ s/$2/$1/g;

现在我意识到在那种状态下,它被错误地读取,因为 $ 在正则表达式中有自己的含义.我在网上做了一些搜索,读到双引号可以解决这个问题,因为它会插入,但这对我不起作用.我不会撒谎,这是一个家庭作业,所以我不期待一个明确的答案.只是朝着正确的方向轻推.

Now I realize in that state, it is being read incorrectly as $ has its own meaning inside of a regexp. I did some searching on the web and read that doublequotes could fix the problem as it would interpolate but that doesn't seen to work for me. I'm not going to lie, this is a homework assignment so I am not expecting a flat out answer. Just a nudge in the right direction.

推荐答案

避免使用 '$1' 和 '$2',因为它们是正则表达式元字符.

Avoid '$1' and '$2' because they are regex metacharacters.

use strict;
use warnings;

my $val1 = "abc";
my $val2 = "def";
while (<>)
{
    s/$val1/$val2/g;
    print;
}

这篇关于如何在正则表达式中使用 Perl 变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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