gpt4 book ai didi

Python - 正则表达式 - 查找所有重复项

转载 作者:行者123 更新时间:2023-12-01 05:21:15 24 4
gpt4 key购买 nike

我正在尝试使用 python 中的以下代码来匹配 html 文本中的电子邮件

my_second_pat = '((\w+)( *?))(@|[aA][tT]|\([aA][tT]\))(((( *?)(\w+)( *?))(\.|[dD][oO][tT]|\([dD][oO][tT]\)))+)([eE][dD][uU]|[cC][oO][mM])'


matches = re.findall(my_second_pat,line)
for m in matches:
s = "".join(m)
email = "".join(s.split())
res.append((name,'e',email))

当我在 line = shoham@stanford.edu

上运行它时

我得到:

[('shoham', 'shoham', '', '@', 'stanford.', 'stanford.', 'stanford', '', 'stanford', '', '.', 'edu')]

我的期望:

[('shoham','@', 'stanford.', 'edu')]

它在 regexpal.com 上作为一个字符串进行匹配,所以我想我在使用 re.findall 时遇到了麻烦

我对正则表达式和Python都很陌生。欢迎任何优化/修改。

最佳答案

试试这个:

(?i)([^@\s]{2,})(?:@|\s*at\s*)([^@\s.]{2,})(?:\.|\s*dot\s*)([^@\s.]{2,})

Regular expression visualization

Debuggex Demo

如果您需要限制为 .com.edu:

(?i)([^@\s]{2,})(?:@|\s*at\s*)([^@\s.]{2,})(?:\.|\s*dot\s*)(com|edu)

Regular expression visualization

Debuggex Demo

请注意,我在正则表达式的开头使用了不区分大小写的标志 (?i),而不是使用 [Ee] 等语法。

关于Python - 正则表达式 - 查找所有重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22292425/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com