Perl——正则表达式(四) 查找替换s///

一. 介绍

使用 s/regex/replacement/modifiers 进行查找替换

二. 实例

(1) s///

$f = "'quoted words'";
#进行模式匹配,下面方法去除''单引号
if($f =~ s/^'(.*)'$/$1/) { #true, $1指的是引用了第一组(.*)的内容, ^$这两个字符用来表示开始与结束

	print "matches","\n"; # mathces
	print $f,"\n";        # quoted words
	                      # 注意 标量$f 匹配后本身内容发生了变化
}

(2) s///r

用它进行匹配后,原始标量的值不会发生变化,可以把新值赋值给一个新的标量

$f = "'quoted words'";
#进行模式匹配,下面方法去除''单引号
$n = $f =~ s/^'(.*)'$/$1/r;

print "matches","\n";
print $f,"\n"; # quoted words   # 注意 标量$f 匹配后本身内容无变化
	
print $n,"\n"; # 'quoted words' # 注意 $n

(3) s///g 多次查找替换

$z = "time hcat to feed the cat hcat";
$z =~ s/cat/AAA/g;#替换多次
print $z,"\n"; #结果为 time hAAA to feed the AAA hAAA

(4) s///e 求值

# reverse all the words in a string
$x = "the cat in the hat";
$x =~ s/(\w+)/reverse $1/ge; # $x contains "eht tac ni eht tah"

# convert percentage to decimal
$x = "A 39% hit rate";
$x =~ s!(\d+)%!$1/100!e; # $x contains "A 0.39 hit rate"

(5) s/// 可以用 s!!! , s{}{} , s{}// 进行替换



  • 4
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值