前端之家收集整理的这篇文章主要介绍了
正则表达式处理文本,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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 data\t 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 @fileds\n";
[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--$3\n";
}
[root@jhoa 2015]# perl c1.pl
Hello--there--neighbor!
非贪婪量词: