Perl——正则表达式(一)字符匹配

来源:互联网 发布:qq飞车解封软件 编辑:程序博客网 时间:2024/05/20 21:45

一. 介绍

#正则表达式"hello world" =~ /world/; 

二. 实例演示

(1) =~ 这个叫做模式绑定操作符,//包含要匹配的字符

if ("hello world" =~ /world/) { # trueprint "matches"; #程序会执行这一步}else {print "no matches";

(2) !~ 这个操作符则与 =~ 取相反的结果

if ("hello world" !~ /world/) { # falseprint "no matches"; }else {print "matches";#程序会执行这一步}


(3)声明标量进行匹配

$s = "hello world";if ( $s =~/world/) { #true print "matches"; #程序会执行这一步}else {print "no matches";}

(4) 省略 $_ =~

如果标量声明时,使用$_作为标量名,则在匹配时可以省略$_ =~

$_ = "hello world";if ( /world/) { #true 省略了 $_ =~print "matches"; #程序会执行这一步}else {print "no matches";}

(5) 保留字符

{}[]()^$.|*+?\
当在正则表达式中使用到保留字符时,要对保留字符进行转义。

"2+2=4" =~ /2+2/;    # doesn't match, + is a metacharacter
"2+2=4" =~ /2\+2/;   # matches, \+ is treated like an ordinary +

(6) m 

//可以用字符m!!的方式来替换

"2+2=4" =~ m!2\+2!;   # matches

0 0
原创粉丝点击