Regexp::Common模块提供了一系列基础的正则表达式,可以非常方便有效的完成许多复杂的文本过滤处理任务,下面简单介绍一些例子,详细信息请参考
- # 标准用法
- use Regexp::Common;
- while (<>) {
- /$RE{num}{real}/ and print q{a number};
- /$RE{quoted}/ and print q{a ['"`] quoted string};
- /$RE{delimited}{-delim=>'/'}/ and print q{a /.../ sequence};
- /$RE{balanced}{-parens=>'()'}/ and print q{balanced parentheses};
- /$RE{profanity}/ and print q{a #*@%-ing word};
- }
- # 函数接口用法
- use Regexp::Common 'RE_ALL';
- while (<>) {
- $_ =~ RE_num_real() and print q{a number};
- $_ =~ RE_quoted() and print q{a ['"`] quoted string};
- $_ =~ RE_delimited(-delim=>'/') and print q{a /.../ sequence};
- $_ =~ RE_balanced(-parens=>'()'} and print q{balanced parentheses};
- $_ =~ RE_profanity() and print q{a #*@%-ing word};
- }
- # 内联用法
- if ( $RE{num}{int}->matches($text) ) {...}
- # ...AND SUBSTITUTION
- my $cropped = $RE{ws}{crop}->subs($uncropped);
- # 自定义
- use Regexp::Common 'pattern';
- pattern name => ['name', 'mine'],
- create => '(?i:J[.]?\s+A[.]?\s+Perl-Hacker)',
- ;
- my $name_matcher = $RE{name}{mine};
- pattern name => [ 'lineof', '-char=_' ],
- create => sub {
- my $flags = shift;
- my $char = quotemeta $flags->{-char};
- return '(?:^$char+$)';
- },
- match => sub {
- my ($self, $str) = @_;
- return $str !~ /[^$self->{flags}{-char}]/;
- },
- subs => sub {
- my ($self, $str, $replacement) = @_;
- $_[1] =~ s/^$self->{flags}{-char}+$//g;
- },
- ;
- my $asterisks = $RE{lineof}{-char=>'*'};
- # DECIDING WHICH PATTERNS TO LOAD.
- use Regexp::Common qw /comment number/; # Comment and number patterns.
- use Regexp::Common qw /no_defaults/; # Don't load any patterns.
- use Regexp::Common qw /!delimited/; # All, but delimited patterns.
子模块Regexp::Common::comment用法
- use Regexp::Common qw /comment/;
- while (<>) {
- /$RE{comment}{C}/ and print "Contains a C comment\n";
- /$RE{comment}{C++}/ and print "Contains a C++ comment\n";
- /$RE{comment}{PHP}/ and print "Contains a PHP comment\n";
- /$RE{comment}{Java}/ and print "Contains a Java comment\n";
- /$RE{comment}{Perl}/ and print "Contains a Perl comment\n";
- /$RE{comment}{awk}/ and print "Contains an awk comment\n";
- /$RE{comment}{HTML}/ and print "Contains an HTML comment\n";
- }
- use Regexp::Common qw /comment RE_comment_HTML/;
- while (<>) {
- $_ =~ RE_comment_HTML() and print "Contains an HTML comment\n";
- }
- # 获取代码里面的注释或者非注释
- my $string = read_file($fileName) ;
- my $comment =~ m/$RE{comment}{Java}/g;
- my $code =~ s/$RE{comment}{Java}//g;
阅读(3046) | 评论(0) | 转发(0) |