第八章 正则表达式的应用
// 相当于m//,相当于m<>
可选的修饰符:
/i 大小写无关: /fred/i
/s 匹配任何字符,使得.可以匹配包括换行符在内的任何字符 /barney.*fred/s
/x 允许在模式中加入任何数量的空白,以方便阅读
这些可以组合使用/fred/is
锚定:
^ 字符串头
$ 字符串尾
/^fred$/能匹配上fred,和fred\n
/^\s*$/匹配空行
词锚定:
\b
/\bfred\b/可匹配单词fred,即全字匹配
非词锚碇 \B
/\bsearch\B/将匹配searchs, searching, 但不能匹配search
=~ 左边表达式和右边模式匹配
if ($some_other =~ /\brub/) xxxx
判断输入字符是否为yes
my $like_perl=(=~ /\byes\b/i);
if ($like_perl) {
xxx
}
正则表达式可以被内插
my $what="larry";
if (/^($what)/) { 相当于/^larry/
xxx
}
my $what=shift @ARGV;通过ARGV来得到模式
匹配变量:括号中的挨个为$1, $2,...
$_="Hello there,neighbor";
if (/\s(\w+),/) { 前面有空格,后面有逗号的一个word
print "the word was $1\n";
}
$1就是第一个匹配的字符串。
如果没有匹配上,匹配变量的值为空串。
如果模式中只有3个或者更少的括号,则$4为undef.
这些匹配变量的值保持不变,直到下一个模式成功匹配为止。所以每次匹配的时候,最好判断一下是
否匹配成功。
if ($wilma=~/(\w+)/) {
print "Wilma's word was $1.\n";
}else {
print "Wilma doesn't have a word.\n";
}
如果在使用匹配变量前要继续其他匹配,请尽快拷贝到普通变量中
my($wilma_word)=$1;
自动匹配变量$& $` $'最好不要使用,会影响性能。
整个匹配的部分在$&中
前一部分在$`,后一部分在$'
if ("Hello there,neighbor" =~ /\s(\w+),/) {
print "That was ($`)($&)($')($1)($2)";
}
输出That was (Hello)( there,)( neighbor)(there)()
一般的数量词
*:0到多
+:1到多
?:0, 1
{}:表示数字范围 /a{5,15}/ 匹配5个到15个a
{3,}3到多
{8} 严格匹配8个 /\w{8}/严格匹配8个word
优先级:
1. () 括号
2. 数量词,包括*, +, ?, {}
3. 猫定和序列 ^, $, \b, \B
4. 竖线 |
习题:
1.
$line=<>;
if ($line =~ /match/) {
print "$`$'";
}
2.
while (<>) {
chomp;
if (/(\w+)a(\s|$)/){
print "Line:$_. Matched one:$&\n";
}
}
3.
while (<>) {
chomp;
if (/(\w+a)(\s|$)/){
print "$1 contains '$1'\n";
}
}
4.
while (<>) {
chomp;
if (/(\w+a)(\W.{0,5})/s){
print "Matched string: $&. the string after matched one:
'$2'\n";
}
}
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/11903161/viewspace-688861/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/11903161/viewspace-688861/