使用正则表达式查找邮箱域名

27 投票
7 回答
57493 浏览
提问于 2025-04-16 15:32

我知道我有点笨,但我就是提取不出这个邮箱地址里的域名:

'blahblah@gmail.com'

我想要的结果是:

'@gmail.com'

我现在得到的结果是:

.

(结果只是一个句号)

这是我的代码:

import re
test_string = 'blahblah@gmail.com'
domain = re.search('@*?\.', test_string)
print domain.group()

我觉得我的正则表达式是这样意思的('@*?.',测试字符串):

 ' # begin to define the pattern I'm looking for (also tell python this is a string)

  @ # find all patterns beginning with the at symbol ("@")

  * # find all characters after ampersand

  ? # find the last character before the period

  \ # breakout (don't use the next character as a wild card, us it is a string character)

  . # find the "." character

  ' # end definition of the pattern I'm looking for (also tell python this is a string)

  , test string # run the preceding search on the variable "test_string," i.e., 'blahblah@gmail.com'

我参考了这里的定义:

http://docs.activestate.com/komodo/4.4/regex-intro.html

另外,我也查过其他答案,但对我来说有点难懂。

非常感谢大家的帮助,像往常一样。谢谢。

我的环境,如果有用的话:

Windows 7 专业版(64位)

Python 2.6(64位)


PS. StackOverflow 问题:我的帖子中不包含换行,除非我在它们之间按“回车”两次。例如(这些在我发帖时都是在不同的行上):

@ - 找到所有以 @ 符号开头的模式

* - 找到 @ 符号后面的所有字符

? - 找到句号前的最后一个字符

\ - 转义(不把下一个字符当作通配符,作为普通字符使用)

. - 找到“.”字符

, 测试字符串 - 在变量“test_string”上运行前面的搜索,也就是 'blahblah@gmail.com'

这就是为什么我在每一行之间都有空行。我到底哪里出错了?谢谢。

7 个回答

8

使用正则表达式:

>>> re.search('@.*', test_string).group()
'@gmail.com'

另一种方法:

>>> '@' + test_string.split('@')[1]
'@gmail.com'
18

好的,那为什么不使用split呢?(或者partition)

"@"+'blahblah@gmail.com'.split("@")[-1]

或者你可以使用其他字符串方法,比如find

>>> s="bal@gmail.com"
>>> s[ s.find("@") : ]
'@gmail.com'
>>>

如果你想从其他文本中提取出电子邮件地址的话

f=open("file")
for line in f:
    words= line.split()
    if "@" in words:
       print "@"+words.split("@")[-1]
f.close()
28

这里有一些我觉得可能会帮到你的东西

import re
s = 'My name is Conrad, and blahblah@gmail.com is my email.'
domain = re.search("@[\w.]+", s)
print domain.group()

输出结果

@gmail.com

这个正则表达式是怎么工作的:

@ - 扫描直到看到这个字符

[\w.] 是一组可能匹配的字符,\w 包括所有字母和数字,后面的句号 . 也算在内。

+ 表示前面那组字符出现一次或多次。

因为这个正则表达式会匹配句号和每个在 @ 后面的字母或数字,所以即使在句子中间,它也能匹配到电子邮件的域名。

撰写回答