python - 使用正则表达式在地址中查找电子邮件域

标签 python regex email search dns

我知道我是个白痴,但我无法从这个电子邮件地址中提取域:

'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 bit)

Python 2.6 (64 bit)


PS。 StackOverflow 问题:我的帖子不包含新行,除非我在它们之间点击“返回”两次。例如(当我发帖时,这些都在不同的行):

@ - 查找以 at 符号 ("@") 开头的所有模式 * - 查找 & 后面的所有字符 ? - 找到句号之前的最后一个字符 \- 突破(不要使用下一个字符作为通配符,我们它是一个字符串字符) . - 找出 ”。”特点 , 测试字符串 - 对变量“test_string”运行前面的搜索,即“blahblah@gmail.com”

这就是为什么我在上面的每一行都有一个空白行。我究竟做错了什么?谢谢。

最佳答案

这里有一些我认为可能会有所帮助的东西

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 都是字母数字字符,并且尾随句点 .添加到该字符集。

+上一组中的一个或多个。

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

关于python - 使用正则表达式在地址中查找电子邮件域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5629907/

相关文章:

python - 如何从python中的字符串中删除连续的相同单词

python - 从元组中提取边集

javascript - 正则表达式第一次出现

objective-c - 我无法打开邮件应用程序?

python - 在python中高效地生成点阵

c# - 正则表达式:尝试多次匹配字符串中任意位置的前缀

Objective-c 正则表达式查看一个字符串是否有多个数字和一个空格?

Javascript - 从输入中删除焦点

mysql - 如何将我的网站用户的电子邮件地址存储在 Aweber 我的 MySQL 数据库中?

python - Python 中的隐写术 - Stepic