加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 23:52:16 所属栏目:大数据 来源:网络整理
导读:一. 介绍 #正则表达式"hello world" =~ /world/; 二. 实例演示 (1) =~ 这个叫做模式绑定操作符,//包含要匹配的字符 if ("hello world" =~ /world/) { # trueprint "matches"; #程序会执行这一步}else {print "no matches"; (2) !~ 这个操作符则与 =~ 取相反

一. 介绍

#正则表达式
"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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读