【问题标题】:Python Regex to extract emailPython Regex 提取电子邮件
【发布时间】:2021-08-06 02:30:41
【问题描述】:

我正在尝试使用 python 来提取sentence that contains the email

sample_str = "This is a random sentence. This one is also random sentence but it contains an email address ---@---.com"

我看到的所有示例都提取了电子邮件,例如:

import re
lst = re.findall('\S+@\S+', sample_str) 

但是无论如何要提取sentence that contains the email。在这种情况下

op = "This one is also random sentence but it contains an email address ---@---.com"

【问题讨论】:

    标签: regex string regex-lookarounds regex-group


    【解决方案1】:

    你可以指出一个句子从哪里开始,中间不要匹配一个句子的结尾。

    但这可能很棘手,并且绝对不是通用解决方案,因为句子不必以字符 [A-Z] 开头,并且可能以与 . ! ? 不同的字符结尾

    作为给定示例的一个想法,您可以使用:

    (?<!\S)[A-Z](?:(?![!?.](?!\S)).)*[^\s@]+@[^\s@]+
    

    说明

    • (?&lt;!\S) 向左声明空白边界
    • [A-Z] 匹配一个字符 A-Z
    • (?:(?![!?.](?!\S)).)* 匹配任何字符,除了 ! ?. 直接后跟空白边界
    • [^\s@]+@[^\s@]+ 匹配邮件格式

    Regex demo | Python demo

    例子

    import re
     
    sample_str = "This is a random sentence. This one is also random sentence but it contains an email address ---@---.com"
    lst = re.findall('(?<!\S)[A-Z](?:(?![!?.](?!\S)).)*[^\s@]+@[^\s@]+', sample_str) 
     
    print(lst)
    

    输出

    ['This one is also random sentence but it contains an email address ---@---.com']
    

    【讨论】:

      猜你喜欢
      • 2021-07-01
      • 2014-05-26
      • 1970-01-01
      • 1970-01-01
      • 2015-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-18
      相关资源
      最近更新 更多