简体   繁体   English

Perl 字符串 - 替换多个字符

[英]Perl String - Substitute Multiple Characters

I couldn't figure out how to change from /usr/lib to /synopsys/vcs/lib/ by only using $mypath=~s/.....;我无法弄清楚如何仅使用$mypath=~s/.....;/usr/lib更改为/synopsys/vcs/lib/ is there anyway to do it?有什么办法吗?

$mypath = "/usr/lib";
$mypath =~ s/usr/synopsys/lib//g;

print "$mypath\n";```

the regex replace works like s/match this / replace with this / In perl you need to escape the forward slash / with a back slash \ then use parentheses to capture usr\/ into $1 So for your example:正则表达式替换的工作方式类似于s/match this / replace with this /在 perl 中,您需要使用反斜杠\转义正斜杠 / 然后使用括号将usr\/捕获到$1所以举个例子:

$mypath =~ s/(usr\/)/$1synopsys\//; 

/ is a special character since it's being used as the delimiter. /是一个特殊字符,因为它被用作分隔符。 If therefore needs to be escaped.如果因此需要转义。

$mypath =~ s/\/usr\/lib/\/synopsys\/vcs\/lib\//;

However, using an alternative delimiter means we wouldn't need all those escapes.但是,使用替代分隔符意味着我们不需要所有这些转义符。

$mypath =~ s{/usr/lib}{/synopsys/vcs/lib/};

That replaces the first instance of /usr/lib contained in the string .这将替换string 中包含/usr/lib的第一个实例。 If you want to replace /usr/lib when it's the entirety of the string, I'd use如果您想在/usr/lib是整个字符串时替换它,我会使用

$mypath = "/synopsys/vcs/lib/" if $mypath eq "/usr/lib";

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

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