2012-05-26 67 views
2

我試圖從正則表達式中使用正則表達式從一串文本中獲取電子郵件地址。從字符串中提取電子郵件,而不是從字符串整行

我怎樣才能讓我的簡單代碼只提取電子郵件地址而不是整行?

demo_text = """hsds hjdsjd ksdkj 

Reason: 550 [email protected] No such user 

sdhjsdjh 
""" 
# the following code extracts the whole line "Reason: 550 [email protected] No such user" 
# how do I just extract "[email protected]"? 
email = re.search("Reason: 550 (.+)... No such user", demo_text).group(0) 

回答

8

.group(0)返回整個字符串。你想.group(1)

email = re.search("Reason: 550 (.*?)... No such user", demo_text).group(1) 
2

取而代之的是組1。

....group(1) 
0

一個更普遍的正則表達式的解決辦法是:

r"[\w.][email protected][\w.]+" 
+1

我想嘗試這一個還有:HTTP:// WWW。 ex-parrot.com/pdw/Mail-RFC822-Address.html。那個只用於驗證,所以我會用它來處理使用這個正則表達式提取的電子郵件。 – Blender

+1

@Blender:我喜歡那個。它簡短,可讀,簡潔:) –

+2

@Joel:請停止傳播** BROKEN **電子郵件地址的正則表達式。 –

-1

只需使用:

email_id = re.search(r'([\w.])[email protected]([\w.])+', demo_text) 
email_id.group(1) # the username part 
email_id.group(2) # the host part 
+0

該正則表達式看起來不正確。我認爲你的意思是使用反斜槓而不是正斜槓 –

+0

@Joel yep我打算使用'\'(ans-replace'/'和'\') – Vivek

+0

@Vivek:請不要指出你的正則表達式會在最簡單的情況下失敗(你省略了許多有效字符);你在兩個*例子中都有錯誤的地方出現了'+'(第一個應該在捕獲組內,第二個在'@'旁邊;即使你把它們正確放置了,你的正則表達式也會捕獲最後的'.'s – Ashe