#! /usr/bin/perl –w
my $what = "fred|test"; # 在此处。| 相当于或的意思
while(<>){
if(/^($what)/){ # 匹配行开头是 fred或test的数据,如果是,通过 if
print "We saw $what in beginning of $_;";
}
}
利用正则:
my $line = 'how old are you?';
$line /(.)\bare\b/ or die "Can't match\n"; # 匹配are,\b为单词边界;
my $string = $1; # 捕获括号中的内容,也就是are之前的内容;
my $n = $string s/ //g; # 将前面的空格换成空,返回成功个数;
print $n+1 ," $line\n"; # 前面的空格数加1就是are单词的位置;
当然,如果你认为用空格数判断单词个数不严谨,也可以改成带字符边界的正则,这里就不多说了.
#! /usr/bin/perl –w
$_ = "Hello there, neighbor";
if(/\s(\w+)/){ #空格和逗号之间的词
print "the word was $1\n"; #the word was there
}
### 在perl 中 $0 输出的是本perl文件的文件名
if(/(\S+) (\S+), (\S+)/){ ###注意正则表达式,有 空格 和 逗号+空格的
print "words were $1 $2 $3";
}
my $dino = "I fear that I'll be extinct after 1000 years.";
if ($dino =~ /(\d*) years/) {
print "That said '$1' years.\n"; # 1000
}
my $dino = "I fear that I'll be extinct after a few millions years.";
if ($dino =~ /(\d*) years/) {
print "That said '$1' years.\n"; # 空串
}
if ("Hello there, neighbor" =~ /\S(\w+),/){
print "That was ($`)($&)($')";
}#That was (Hello )(there,)( neighbor)
正则表达式 例子
最新推荐文章于 2018-07-08 13:09:23 发布
本文通过多个实例展示了Perl中正则表达式的使用方法,包括如何匹配特定字符串、捕获子串以及处理边界条件等。文章适合希望深入了解Perl正则表达式应用的读者。
2714

被折叠的 条评论
为什么被折叠?



