2014-10-07 83 views
0

不工作我已經在這裏上傳吧..Python的正則表達式的代碼

http://regex101.com/r/hC2eH3/1

讓email.body =

> From: "FastTech" <[email protected]> 
> 
> == Ship to == 
> Example Name 
> 
> Shipping via Registered Airmail w/Tracking 
> 
> == Shipping ETA == 
> 
> == Items ordered == 
> 
> == Other services == 
> 
> 
> == Order total == 
> $2.63 
> 
> 
> 
> 
> Thank you again for choosing FastTech. 
> 
> Kind regards, 
> 
> The FastTech Team 
> 
> 
> FastTech - gadget and electronics 
> http://www.fasttech.com 
> [email protected] 
> 
> 
> This email was automatically generated for 

我不能得到這個在我的劇本的工作 - 使用此代碼:

regex = r'> == Ship to == *\n. (\w+\s\w+)' 
    link = re.findall(regex, email.body) 
    print link 

打印鏈接只是返回

[]

當它應該是匹配的 '實例名稱'

+0

您的預期輸出是什麼? – 2014-10-07 10:13:40

+0

我已更新OP – Andy 2014-10-07 10:15:17

+0

您的問題在於email.body。正則表達式工作正常。嘗試打印email.body。看到它的真實價值 – 2014-10-07 10:19:46

回答

1

你的正則表達式工作正常,我。

>>> import re 
>>> s = """> From: "FastTech" <[email protected]> 
... > 
... > == Ship to == 
... > Example Name 
... > 
... > Shipping via Registered Airmail w/Tracking 
... > 
... > == Shipping ETA == 
... > 
... > == Items ordered == 
... > 
... > == Other services == 
... > 
... > 
... > == Order total == 
... > $2.63 
... > 
... > 
... > 
... > 
... > Thank you again for choosing FastTech. 
... > 
... > Kind regards, 
... > 
... > The FastTech Team 
... > 
... > 
... > FastTech - gadget and electronics 
... > http://www.fasttech.com 
... > [email protected] 
... > 
... > 
... > This email was automatically generated for """ 
>>> m = re.findall(r'> == Ship to == *\n. (\w+\s\w+)', s) 
>>> m 
['Example Name'] 

OR

你可以試試這個。單個空間將完全匹配\s*將匹配零個或多個空格的空間。所以最好使用\s*而不是空格。

>>> m = re.findall(r'^\s*>\s*==\s*Ship\s*to\s*==\s+>\s*(\w+\s\w+)', s, re.M) 
>>> m 
['Example Name'] 
+0

這有效......爲什麼不是我的?感謝您的答案:-)這是我第一次嘗試正則表達式.. – Andy 2014-10-07 10:24:19

+0

@安迪它可能或可能不包含一個或多個空間..你總是歡迎:-) – 2014-10-07 10:28:54