大家用过unix或者linux系统,对vi,sed,grep,awk等使用工具不会陌生,应该了解用于定界符搜索模式的正则表达式和元字符。那么什么是正则表达式呢?正则表达式是一种序列或者字符模式,负责在搜索或者替换文本时对文本内容进行字符串匹配。简单的正则表达式直接由待匹配字符串或字符集构成。
正则表达式一般以斜杠(/)做界定符。实际上任何字符串都可以成为界定符。例如:/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
正则表达式运算符
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表达修饰符用于在正则表达式中放入注释或者空白字符,以便让正则表达式含义更明确。
demo
(1) $_="San Francisco to * \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