2011-01-12 42 views
1

我试图创造出符合以下正则表达式域:Perl的正则表达式匹配只有1

[email protected]

1部分:第一部分,其中任何5位数字,从0-9
第二部分:[可选]其中,@ domain.com是,除了所有的域@ yahoo.com

例如:[email protected]
我无法找到如何插入conditiona l进入正则表达式。现在只有我的正则表达式匹配数字+域。仍需要弄清楚:

  1. 如何只匹配位数
  2. 有条件接受除@ yahoo.com

代码的所有领域:

#!/usr/bin/perl 
use strict; 
use warnings; 

my $regex1 = '^(\d{5})([@]([a-zA-Z0-9_-]+?\.[a-zA-Z]{2,6})+?)'; 

while (my $line = <DATA>) { 
    chomp $line; 
    if ($line =~ /$regex1/) 
    { 
    print "MATCH FOR:\t$line \n"; 
    } 
} 

样品数据:

1234 
[email protected] 
[email protected] 
[email protected] 
12345 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
+0

这似乎是一个问题,可以解决不使用正则表达式。我对你走这条路的原因很好奇(不是说我是一个正则表达者或者任何东西,就好像你在用火箭发射器杀死一只老鼠一样) – Terrance 2011-01-20 13:46:47

回答

2

何不干脆先检查yahoo.com,如果你得到一个比赛去下一行:

while (my $line = <DATA>) { 
    chomp $line; 
    next if ($line =~ /yahoo\.com$/); 
    if ($line =~ /$regex1/) 
    { 
    print "MATCH FOR:\t$line \n"; 
    } 
} 
2

这个怎么样?

\d{5}(?:@(?!yahoo)[a-zA-Z0-9.]+\.[a-zA-Z]{2,3})? 

在扩展形式:

\d{5}   # 5 digits 
(?:    # begin a grouping 
    @    # literal @ symbol 
    (?!yahoo\.com) # don't allow something that matches 'yahoo.com' to match here 
    [a-zA-Z0-9.]+ # one or more alphanumerics and periods 
    \.    # a literal period 
    [a-zA-Z]{2,3} # 2-3 letters 
)    # end grouping 
?    # make the previous item (the group) optional 

(?!yahoo\.com)是什么叫做 “negative lookahead assertion”。