背景:
Perl的正则表达式非常强大,但其使用方式却很简单,而且匹配与替换是应用最多的操作.至于如何写正则模式,则不是这篇短文要做的了.
正文:
类Rge.pm
package Reg; use Exporter; #父类必须
@ISA = qw(Exporter); #父类必须
@EXPORT = qw(matchPat, replacePat); #父类必须,释放出该成员方法,以便继承
sub new{ my $type = shift; my $this = {}; bless $this, $type; return $this; }
sub matchPat{ my $this = shift; my $str = shift; my $pat = shift; if($str =~ /$pat/){ #在$str中匹配模式,返回BOOL值 print $str; } else{ print "no"; } print "\n"; }
sub replacePat{ my $this = shift; my $str = shift; my $pat = shift; my $desStr = shift; my $flag = shift; if(1 == $flag){ $str =~ s/$pat/$desStr/g; } else{ $str =~ s/$pat/$desStr/; } return $str; } 1;
|
调用
use Reg; use strict;
###Reg my $reg = new Reg; #matching my $str = " TCP 192.168.128.232:3313 192.168.128.91:445 ESTABLISHED"; my $str2 = " TCP 0.0.0.0:80 0.0.0.0:0 LISTENING"; my $pat = ' +TCP +(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d{1,4} +){2}\w'; $reg->matchPat($str, $pat); #replace my $pat2 = '\d{1,3}\.'; my $str3 = "x|"; $reg->replacePat($str2, $pat2, $str3, 1); ###Reg end
|
阅读(575) | 评论(0) | 转发(0) |