標籤:io os 使用 sp for on bs ef amp
大家用過unix或者linux系統,對vi,sed,grep,awk等使用工具不會陌生,應該瞭解用於定界符搜尋模式的Regex和元字元。那麼什麼是Regex呢?Regex是一種序列或者字元模式,負責在搜尋或者替換文本時對常值內容進行字串匹配。簡單的Regex直接由待匹配字串或字元集構成。
Regex一般以斜杠(/)做界定符。實際上任何字串都可以成為界定符。例如:/abc/, ?abc?
運算式修飾符與簡單語句
常見修飾符:if unless while until foreach
if條件修飾符
格式 Expression2 if Expression1 如果Expression1運算式為真,則執行Expression2運算式內容。
demo
(1) $x=5;
print $x if x==5; ====>輸出5
(2) $_="xabcy\n";
print if /abc/; ====>輸出xabcy
(3) $_="I lost my gloves in the clover.";
print "Found love in gloves!\n" if /love/; ====>輸出Found love in gloves!
unless修飾符
格式 Expression2 unless Expression1 如果Expression1為假,則執行Expression2運算式內容。
demo
(1) $x=5;
print $x unless $x==6; ====>輸出5
while迴圈修飾符
格式 Expression2 while Expression1 只要第一個運算式為真,while迴圈修飾符便會重複執行第二個運算式。
demo
(1) $x=1;
print $x++,"\n" while $x!=5; ====>輸出1,2,3,4
until修飾符
格式 Expression2 until Expression1 只要第一個運算式為假, while迴圈修飾符便會重複執行第二個運算式
demo
(1) $x=1;
print $x++,"/n" until $x==5; ====>輸出1,2,3,4
foreach修飾符
會逐個判斷列表中每個元素的值,並通過標量$_以此引用各個列表元素。
demo
(1) @alpha=(a .. z,"\n");
print foreach @alpha; ====>abcdefghijkmnopqrstuvwxyz
Regex運算子
m運算子與匹配
demo
(1) while (<DATA>){
print if /Betty/ ====>輸出 Betty Boop
}
__DATA__
Steve Blenheim
Betty Boop
Igor Chevsky
Norma Cord
(2)while (<DATA>){
print if m#Jon#; ====>輸出Jon DeLoach
}
__DATA__
Steve Blenheim
Betty Boop
Igor Chevsky
Norma Cord
Jon DeLoach
g全域修飾符
i修飾符:大小寫不敏感
demo
(1)$_="I lost my gloves in the clover,Love.";
@list=/love/gi;
print "@list . \n"; ====>love love Love
x表達修飾符用於在Regex中放入注釋或者空白字元,以便讓Regex含義更明確。
demo
(1) $_="San Francisco to Hong Kong \n";
/Francisco
/x;
print "Comments and spaces were removed and \$& is $&\n"; ====>輸出Comments and spaces were removed and $& is Francisco
S運算子與替換
demo
(1)$_="knock at heaven‘s door. \n";
s/knock/"knock," *2."knocking"/ei;
print "He‘s $_"; ====>He‘s knock,knock,knocking at heaven‘s door.
模式綁定運算子
=~ !~
demo
(1) while($_=<DATA>){
print $_if $_=~/Igor/; ====>輸出Igor Chevsky
}
__DATA__
Steve Blenheim
Betty Boop
Igor Chevsky
Norma Cord
(2) while ($_=<DATA>){
print $_ if $_!~/Igor/; ====>輸入除Igor Chevsky以外的名稱
}
__DATA__
Steve Blenheim
Betty Boop
Igor Chevsky
Norma Cord
Perl之Regex--模式比對