我知道我是个白痴,但我无法从这个电子邮件地址中提取域:
'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/