我有一个perl脚本 -
#!/usr/bin/perl;
my $email = '[a-zA-Z0-9._]+@[a-zA-Z0-9._]+.[a-zA-Z0-9._]{2,4}';
open(FILE,'emails');
while (<FILE>) {
my $emails_not_found = 1;
if ( m/$email/ ) {
print($_);
my $emails_not_found = 0;
}
if ( $emails_not_found ) {
print "no emails\n";
}
}
close FILE;
文件emails
是:
sdfasd@asd
asdf
所以,正如您所看到的,脚本将不会将正则表达式与任何行匹配。但是,它会输出 -
no emails
no emails
如果它与正则表达式模式完全匹配,我希望它输出'无电子邮件'ONCE。如果它只匹配正则表达式模式一次,它将打印该行并输出另一个“无电子邮件” line :(我只是希望它输出JUST与电子邮件的行,或输出1行“没有电子邮件”。提前感谢。
答案 0 :(得分:3)
考虑使用模块,例如Regexp::Common::Email::Address,“...以匹配RFC 2822定义的电子邮件地址”:
use strict;
use warnings;
use Regexp::Common qw/Email::Address/;
my $emailFound = 0;
open my $fh, '<', 'emails' or die $!;
while (<$fh>) {
if (/$RE{Email}{Address}/) {
print;
$emailFound = 1;
}
}
close $fh;
print "no emails\n" if !$emailFound;
希望这有帮助!
答案 1 :(得分:2)
试试这个,我更改了电子邮件文件名,以便在我的机器上进行测试:
#!/usr/bin/perl
#output either JUST the lines with emails
# or
#1 line that says 'no emails'
use strict;
use warnings;
my $email = '[a-z0-9\._]+@[a-z0-9\._]+\.[a-z0-9\._]{2,4}';
open(FILE,'./email.txt');
my $emails_not_found = 1;
while (<FILE>) {
if ( m/$email/i ) {
print($_);
$emails_not_found = 0;
}
}
if ( $emails_not_found == 1) {
print "no emails\n";
}
close FILE;
sdfasd@asd
asdf
aaa@aaa.com
AAA@AAA.COM
aaa@aaa.com
AAA@AAA.COM