Perl——正则表达式(四) 查找替换s///
发布时间:2020-12-15 23:52:12 所属栏目:大数据 来源:网络整理
导读:一. 介绍 使用? s/regex/replacement/modifiers 进行查找替换 二. 实例 (1) s/// $f = "'quoted words'";#进行模式匹配,下面方法去除''单引号if($f =~ s/^'(.*)'$/$1/) { #true,$1指的是引用了第一组(.*)的内容,^$这两个字符用来表示开始与结束print "matche
一. 介绍
二. 实例(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{}// 进行替换 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |