1. 程式人生 > >Perl——正則表示式(四) 查詢替換s///

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{}// 進行替換