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

前端之家收集整理的这篇文章主要介绍了Perl——正则表达式(一)字符匹配前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

一. 介绍

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

二. 实例演示

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

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

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

if ("hello world" !~ /world/) { # false
	print "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

猜你在找的Perl相关文章