zoukankan      html  css  js  c++  java
  • Perl——正则表达式(四) 查找替换s///

    转自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","
    "; # mathces  
    6     print $f,"
    ";        # quoted words  
    7                           # 注意 标量$f 匹配后本身内容发生了变化  
    8 }  


    (2) s///r

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

    1 $f = "'quoted words'";  
    2 #进行模式匹配,下面方法去除''单引号  
    3 $n = $f =~ s/^'(.*)'$/$1/r;  
    4   
    5 print "matches","
    ";  
    6 print $f,"
    "; # quoted words   # 注意 标量$f 匹配后本身内容无变化  
    7       
    8 print $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,"
    "; #结果为 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{}// 进行替换

  • 相关阅读:
    fastjson反序列化
    BaseBean构造
    easyUI_rowdata
    SVN提交报错
    jsp页面数据保留两位小数
    数据库 建立
    增删改查问
    解决plsql中文乱码问题
    oracle_解锁表
    ibatis_compareValue
  • 原文地址:https://www.cnblogs.com/yiyedada/p/6714329.html
Copyright © 2011-2022 走看看