2011-01-12 70 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」。