正则表达式提取邮箱的顶级域名
从像这样的电子邮件地址
xxx@site.co.uk
xxx@site.uk
xxx@site.me.uk
我想写一个正则表达式,应该在所有情况下都返回'uk'。
我尝试过
'+@([^.]+)\..+'
但是它只返回了域名。我还尝试使用
'[^/.]+$'
但它出现了错误。
4 个回答
0
简单的 .*\.(\w+)
这个表达式可能不够用?
如果需要的话,可以在这个正则表达式中添加更多对“@”的验证。
2
因为 myemail@com
是一个有效的邮箱地址,你可以使用:
@.*([^.]+)$
2
你不需要用正则表达式。在你的例子中,这段代码总是会给你'uk'的结果:
>>> url = 'foo@site.co.uk'
>>> url.split('.')[-1]
'uk'
3
提取你想要的内容的正则表达式是:
\.([^.\n\s]*)$ with /gm modifiers
解释:
\. matches the character . literally
1st Capturing group ([^.\n\s]*)
[^.\n\s]* match a single character not present in the list below
Quantifier: Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
. the literal character .
\n matches a fine-feed (newline) character (ASCII 10)
\s match any white space character [\r\n\t\f ]
$ assert position at end of a line
m modifier: multi-line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)
g modifier: global. All matches
对于你的输入示例,它将是:
import re
m = re.compile(r'\.([^.\n\s]*)$', re.M)
f = re.findall(m, data)
print f
输出:
['uk', 'uk', 'uk']
希望这对你有帮助。