2010-07-26 147 views
2

之前找到電子郵件地址的部分我在Perl.I中有下面這個問題。我有一個文件,我在其中獲取電子郵件列表作爲輸入。Perl正則表達式在@

我想解析所有電子郵件地址中'@'之前的字符串。 (稍後我會將@之前的所有字符串存儲在數組中)

例如,在:[email protected],我想解析電子郵件地址並提取abcdefgh。

我的意圖是隻在'@'之前得到字符串。現在的問題是如何使用正則表達式來檢查它。或者是否有任何其他方法使用substr?

雖然我在Perl中使用正則表達式:$ mail =〜「\ @」,但它並未給出結果。

此外,我將如何查找字符'@'是字符串$ mail的索引?

我很感謝有人能幫助我。

#!usr/bin/perl 

$mail = "[email protected]"; 

if ($mail =~ "\@") { 
    print("my name = You got it!"); 
} 
else 
{ 
    print("my name = Try again!"); 
} 

在上面的代碼$郵件=〜 「\ @」 沒有給我想要的輸出,但($郵件=〜 「ABC」)一樣。

$ mail =〜「@」只有在給定的字符串$ mail =「abcdefgh \ @ gmail.com」時纔有效。

但在我的情況下,我會得到與其電子郵件地址的輸入。

不帶轉義字符。

感謝,

湯姆

回答

1

,如果你想這是什麼:

my $email = '[email protected]'; 

$email =~ /^(.+?)@/; 
print $1 

$ a1將是@前面的一切。

2

@符號是雙引號字符串中的元字符。如果你把你的電子郵件地址放在單引號中,你就不會遇到這個問題。

此外,如果您只是在嘗試,我應該添加必要的評論,但在生產代碼中,您不應使用正則表達式解析電子郵件地址,而應使用諸如Mail::Address之類的模塊。

+0

[電子郵件地址](http://p3rl.org/Email::Address)更好。 – daxim 2010-07-26 16:44:52

0

如果你想要一個字符串的索引,你可以使用index()函數。即。

my $email = '[email protected]'; 
my $index = index($email, '@'); 

如果你想返回的電子郵件的前半部分,我會使用split()了正則表達式。

my $email = '[email protected]'; 
my @result = split '@', $email; 
my $username = $result[0]; 

或用substr

my $username = substr($email, 0, index($email, '@')) 
+0

您應該在此代碼中使用rindex來查找最後@而不是第一個。根據rfc2822,'@'在本地部分('$ username')中作爲引用字符串的一部分是有效的。 – 2010-07-26 21:51:26

6

啓用警告甚至更好會指出你的問題:

#!/usr/bin/perl 
use warnings; 

$mail = "[email protected]"; 
__END__ 
Possible unintended interpolation of @gmail in string at - line 3. 
Name "main::gmail" used only once: possible typo at - line 3. 

並啓用嚴格的會從連編譯阻止它:

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

my $mail = "[email protected]"; 
__END__ 
Possible unintended interpolation of @gmail in string at - line 4. 
Global symbol "@gmail" requires explicit package name at - line 4. 
Execution of - aborted due to compilation errors. 

換句話說,你的問題不是正則表達式工作或不工作,而是你匹配的字符串包含「abcdefgh.com」,而不是你所期望的。