Python正则表达式,在地址中找到电子邮件域

我知道我是个白痴,但我不能从这个电子邮件地址中删除该域名:
'blahblah@gmail.com'
我想要的输出:
'@gmail.com'
我目前的输出:
.
(这只是一个时期角色) 这是我的代码:
import re
test_string = 'blahblah@gmail.com'
domain = re.search('@*?.', test_string)
print domain.group()
这是我认为我的正则表达式('@ *?。',test_string):
 ' # 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 Pro(64位)      Python 2.6(64位) PS。 StackOverflow问题:我的帖子不包括新行,除非我在它们之间点击两次“返回”。例如(当我发帖时,这些都在不同的行上): @ - 查找以at符号(“@”)开头的所有模式 * - 在&符号后找到所有字符 ? - 找到期间之前的最后一个字符 - breakout(不要将下一个字符用作外卡,我们这是一个字符串字符) 。 - 找出 ”。”字符 ,test string - 在变量“test_string”上运行前面的搜索,即'blahblah@gmail.com' 这就是为什么我在每一行上面都有一个空行b / w。我究竟做错了什么?谢谢。     
已邀请:
这是我认为可能会有所帮助的东西
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
是所有字母数字字符,尾随句号
.
会添加到该字符集。
+
前一组中的一个或多个。 因为这个正则表达式匹配句点字符和
@
之后的每个字母数字,所以它甚至会在句子中间匹配电子邮件域。     
好的,为什么不使用拆分? (或分区)
"@"+'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()
    

bab

使用正则表达式:
>>> re.search('@.*', test_string).group()
'@gmail.com'
另一种方式:
>>> '@' + test_string.split('@')[1]
'@gmail.com'
    
只想指出chrisaycock的方法将匹配表单的无效电子邮件地址
herp@
要正确确保您只是将可能有效的电子邮件与域匹配,您需要稍微改变它 使用正则表达式:
>>> re.search('@.+', test_string).group()
'@gmail.com'
    
使用下面的正则表达式,您可以提取任何域名,如.com或.in。
import re
s = 'my first email is user1@gmail.com second email is enter code hereuser2@yahoo.in and third email is user3@outlook.com'
print(re.findall('@+S+[.in|.com|]',s))
产量
['@gmail.com', '@yahoo.in']
    

要回复问题请先登录注册