Perl语言入门笔记 第七章 漫游正则表达式王国

=pod
正则表达式(regular expression),在perl里面通常也叫做模式(pattern),是用来表示匹配或不匹配某个字符串的特征模板。
	文件名通配与正则表达式是两个概念。
grep指令:
	$grep 'flint.*stone' chapter*.txt #查看chaper*.txt文件中,有哪行出现过flint且后面跟着stone
	
使用简单模式:
	$_ = "yabba dabba doo";
	if(/abba/)
	{
		print "Matched!\n";
	}
	有许多字符属于空白符,相应属性为space;
	if(/\p{Space}/)
	{
		print "The string has some whitespace\n";
	}
	如果要匹配数字,可以用Digit属性:
		if(/\p{Digit}/)
		[
			print "The string has digit.\n";
		}
	检查连续含有两个十六进制的字符:
		if(/\p{Hex}\p{Hex}/) #\p表示匹配后面跟的属性的意思
		{
			print "The string has a pair of hex digits\n";
		}
		\P表示不匹配后面跟的属性
		
元字符: 元字符前面加上反斜线,元字符就失去了它原有的属性
	.	匹配除\n外所有的字符,一个
	匹配\需要一个\线来转义
	
简单的量词:
	*	匹配前面的那个字符的0次或多次
	.*	匹配任意多个字符(除\n外),俗称捡破烂(any old junk)
	+	匹配一个或多个
	?	匹配一个或零个
	()	对字符串分组
	/(fred)+/	匹配fredfredfred类的字符串
	
	$_ = "abba"; #匹配'bb'
	if(/(.)\1) #\1是反向引用
	{	}
	$_ = "yabba dabba doo";
	if(/y(.)(.)\2\1/) #匹配'abba'
	
use 5.010;
$_ = "aa11bb";	
if(/(.)\g{1}11){}	#\g{N}写法

use 5.010;
$_ = "xaa11bb";
if(/(.)(.)\g{-1}11/) { } #反向引用,相对于自己的位置

择一匹配:
	竖线|通常读作或,fred|barney|betty能匹配任何含有fred或者barney或者betty的字符串
	/fred(|\t)+barney/	匹配fred和barney之间出现一次以上空格、制表符或两者混合的字符串。加号表示重复一次或更多。每次只要有重复,(|\t)就能匹配空格或制表符,在这两个名字之间至少要有一个空格或制表符。
	/fred(+|\t+)barney/ 中间不是空格就是\t
	/fred(and|or)barney/匹配含有fredandbarney或者fredorbarney

字符集:
	[a-zA-Z] [^adg] 匹配其中的一个,或除其中的一个
	\h	匹配水平空白符
	\v	匹配垂直空白符	\h+\v = \p{Space}
	\R	匹配任意一种断行符,如\r\n还是\n
	\w	匹配任意字符0-9a-zA-Z,下划线也是的

反义简写:
	[^\d] = [\D]
	[^\w] = [\W]
	[^\s] = [\S]
	[\d\D]	匹配任意字符,包括换行
	[^\d\D]	什么都不匹配
	
	
=cut


简单练习:

#!/usr/bin/perl -w
use strict;
=pod
#ex7_1
while(1)
{
	chomp(my $line = <STDIN>);
	($line =~ /fred/) and print "$line\n";	
}
=cut
=pod
#ex7_2
while(1)
{
	chomp(my $line = <STDIN>);
	($line =~ /[Ff]red/) and print "$line\n";	
}
=cut

=pod
#ex7_3
while(1)
{
	chomp(my $line = <STDIN>);
	($line =~ /\./) and print "$line\n";	
}
=cut
=pod
#ex7_4
while(1)
{
	chomp(my $line = <STDIN>);
	($line =~ /^[A-Z][a-zA-Z]*[a-z]+[a-zA-Z]*/) and print "$line\n";	
}
=cut
=pod
#ex7_5
while(1)
{
	chomp(my $line = <STDIN>);
	($line =~ /(\S)\1/) and print "$line\n";	
}
=cut

while(1)
{
	chomp(my $line = <STDIN>);
	($line =~ /[\d\D]*wilma[\d\D]*fred[\d\D]*|[\d\D]*fred[\d\D]*wilma[\d\D]*/) and print "$line\n";	
}


system "pause";


posted @ 2015-09-21 01:40  笑面浮屠  阅读(159)  评论(0编辑  收藏  举报