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

来源:互联网 发布:网络视频直播平台排行 编辑:程序博客网 时间:2024/06/06 01:05

一. 介绍

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

二. 实例

(1) s///

$f = "'quoted words'";#进行模式匹配,下面方法去除''单引号if($f =~ s/^'(.*)'$/$1/) { #true, $1指的是引用了第一组(.*)的内容, ^$这两个字符用来表示开始与结束print "matches","\n"; # mathcesprint $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{}// 进行替换



0 0
原创粉丝点击