Python正则表达式不能在代码中工作

时间:2014-10-07 10:11:17

标签: python regex

我已将其上传到此处..

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

让email.body =

> From: "FastTech" <support@fasttech.com>
>
> == 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
> support@fasttech.com
>
>
> This email was automatically generated for 

我无法在我的脚本中使用此代码 - 使用此代码:

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

打印链接只返回

[]

应该匹配&#39;示例名称&#39;

1 个答案:

答案 0 :(得分:1)

你的正则表达式适用于我。

>>> import re
>>> s = """> From: "FastTech" <support@fasttech.com>
... >
... > == 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
... > support@fasttech.com
... >
... >
... > This email was automatically generated for """
>>> m = re.findall(r'> == Ship to == *\n. (\w+\s\w+)', s)
>>> m
['Example Name']

你可以试试这个。单个空格将恰好匹配\s*将匹配零个或多个空格的空间。因此,最好使用\s*而不是空格。

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