• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Perl——正则表达式(四)查找替换s///

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

转自http://blog.csdn.net/blog_abel/article/details/40589227 侵删

一. 介绍

使用 s/regex/replacement/modifiers 进行查找替换

二. 实例

(1) s///

 

1 $f = "'quoted words'";  
2 #进行模式匹配,下面方法去除''单引号  
3 if($f =~ s/^'(.*)'$/$1/) { #true, $1指的是引用了第一组(.*)的内容, ^$这两个字符用来表示开始与结束  
4   
5     print "matches","\n"; # mathces  
6     print $f,"\n";        # quoted words  
7                           # 注意 标量$f 匹配后本身内容发生了变化  
8 }  


(2) s///r

 

用它进行匹配后,原始标量的值不会发生变化,可以把新值赋值给一个新的标量

1 $f = "'quoted words'";  
2 #进行模式匹配,下面方法去除''单引号  
3 $n = $f =~ s/^'(.*)'$/$1/r;  
4   
5 print "matches","\n";  
6 print $f,"\n"; # quoted words   # 注意 标量$f 匹配后本身内容无变化  
7       
8 print $n,"\n"; # 'quoted words' # 注意 $n  

 

 


(3) s///g 多次查找替换

1 $z = "time hcat to feed the cat hcat";  
2 $z =~ s/cat/AAA/g;#替换多次  
3 print $z,"\n"; #结果为 time hAAA to feed the AAA hAAA  
 


(4) s///e 求值

1 # reverse all the words in a string  
2 $x = "the cat in the hat";  
3 $x =~ s/(\w+)/reverse $1/ge; # $x contains "eht tac ni eht tah"  
4   
5 # convert percentage to decimal  
6 $x = "A 39% hit rate";  
7 $x =~ s!(\d+)%!$1/100!e; # $x contains "A 0.39 hit rate"  

 

(5) s/// 可以用 s!!! , s{}{} , s{}// 进行替换


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
writeyourselfownperlmodule发布时间:2022-07-22
下一篇:
《SED单行脚本快速参考》的perl实现发布时间:2022-07-22
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap