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

正则表达式处理文本

发布时间:2020-12-14 01:24:44 所属栏目:百科 来源:网络整理
导读:s/// 替换:[root@jhoa 2015]# cat b1.pl $_="He's out bowling with Barney tonight.";s/Barney/Fred/;print "$_ is $_n";[root@jhoa 2015]# perl b1.pl $_ is He's out bowling with Fred tonight.用/s 来匹配任意字符 默认情况下,点号(.)无法匹配换行符,
s/// 替换:

[root@jhoa 2015]# cat b1.pl 
$_="He's out bowling with Barney tonight.";
s/Barney/Fred/;
print "$_ is $_n";

[root@jhoa 2015]# perl b1.pl 
$_ is He's out bowling with Fred tonight.


用/s 来匹配任意字符  默认情况下,点号(.)无法匹配换行符,这对大多数单行匹配的情况是合适的。

. 圆点用于匹配除换行符外的任何单个字符

+ 意味着一个或多个相同的字符



.+  匹配任意单个字符至少一次

.* 所有任意数量字符。与前一字符结合,可不出现字符

-? ##零个或一个减号

d+  #一个或多个数字

.?  #零个或一个小数点

d*  ##零个或多个数字

S 非空白

s 空白 n t r f

w 英文字母和数字的字符窜


W 非英文字母和数字的字符串


$_="He's out bowling with Fred tonight.";
s/with (w+)/against $1's team/;
print "$_ is $_n";

[root@jhoa 2015]# perl b2.pl 
$_ is He's out bowling against Fred's team tonight.


[root@jhoa 2015]# cat b3.pl 
$_="green scaly dinosaur";
s/(w+) (w+)/$2,$1/;
print "$_ is $_n";


[root@jhoa 2015]# perl b3.pl 
$_ is scaly,green dinosaur



[root@jhoa 2015]# cat b3.pl 
$_="green scaly dinosaur";
#s/(w+) (w+)/$2,$1/;

s/^/huge,/;
print "$_ is $_n";
[root@jhoa 2015]# perl b3.pl 
$_ is huge,green scaly dinosaur

开头加上huge,/g 全局匹配:

[root@jhoa 2015]# cat b4.pl 
$_="home,sweet home!";
s/home/cave/g;
print "$_ is $_n";
[root@jhoa 2015]# perl b4.pl 
$_ is cave,sweet cave!


将多个空格转换为单个空格
[root@jhoa 2015]# cat b5.pl 
$_="input datat may have    extra      whitespace.   ";
s/s+/ /g;
print "$_ is $_n";
[root@jhoa 2015]# perl b5.pl 
$_ is input data may have extra whitespace.



split 函数:

[root@jhoa 2015]# cat b6.pl 
@fileds = split /:/,"abc:def:g:h";
print "@fields is @filedsn";
[root@jhoa 2015]# perl b6.pl 
@fields is abc def g h


join 函数:
[root@jhoa 2015]# cat b7.pl 
my @old = qw/a b c d e f g/;
my @new = join "xx",@old;
foreach (@new){
print "$_ is $_n";
}
[root@jhoa 2015]# perl b7.pl 
$_ is axxbxxcxxdxxexxfxxg





列表上下问的m //

[root@jhoa 2015]# cat c1.pl 
$_ = "Hello there,neighbor!";

if ($_ =~ /(S+) (S+),(S+)/){

print "$1--$2--$3n";
}
[root@jhoa 2015]# perl c1.pl 
Hello--there--neighbor!


非贪婪量词:

(编辑:李大同)

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

    推荐文章
      热点阅读