正则表达式 例子

本文通过多个实例展示了Perl中正则表达式的使用方法,包括如何匹配特定字符串、捕获子串以及处理边界条件等。文章适合希望深入了解Perl正则表达式应用的读者。
#! /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)

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值