我是新手,对Python和正则表达式都不太熟悉。我想知道如何提取电子邮件地址的第一部分,直到域名为止。例如:
s='xjhgjg876896@domain.com'
我希望正则表达式的结果能够考虑到所有可能的电子邮件地址格式,包括数字等等。
xjhgjg876896
我了解正则表达式的概念-即我知道需要扫描到“@”并存储结果-但我不确定如何在Python中实现它。
谢谢您的时间。
您需要使用正确的RFC5322解析器。
"@@@@@"@example.com
是一个有效的电子邮件地址,语义上的本地部分("@@@@@"
)与其用户名(@@@@@
)不同。
从python3.6开始,您可以使用email.headerregistry
:
from email.headerregistry import Address
s='xjhgjg876896@domain.com'
Address(addr_spec=s).username # => 'xjhgjg876896'
正如其他人指出的那样,更好的解决方案是使用 split
。
如果您确实想使用 regex
,则可以尝试以下方法:
import re
regexStr = r'^([^@]+)@[^@]+$'
emailStr = 'foo@bar.baz'
matchobj = re.search(regexStr, emailStr)
if not matchobj is None:
print matchobj.group(1)
else:
print "Did not match"
然后它会输出
foo
注意: 本方法仅适用于形如 SOMEONE@SOMETHING.TLD
的电子邮件字符串。如果您想匹配类型为 NAME<SOMEONE@SOMETHING.TLD>
的电子邮件,请调整正则表达式。
你不应该使用正则表达式或 split
函数。
local, at, domain = 'john.smith@example.org'.rpartition('@')
prefix, _, _ = 'john.smith@example.org'.rpartition('@')
。 - ikrebprefix,_,_ ='john.smith@example.org'.rpartition('@')
。 - ikrebs='xjhgjg876896@domain.com'
# Now lets find the location of the "@" sign
index = s.index("@")
# Next lets get the string starting from the begining up to the location of the "@" sign.
s_id = s[:index]
print(s_id)
而且输出是
xjhgjg876896
#!/usr/bin/python3.6
def email_splitter(email):
username = email.split('@')[0]
domain = email.split('@')[1]
domain_name = domain.split('.')[0]
domain_type = domain.split('.')[1]
print('Username : ', username)
print('Domain : ', domain_name)
print('Type : ', domain_type)
email_splitter('foo.goo@bar.com')
Username : foo.goo
Domain : bar
Type : com
foo.goo@here.domain.com
。 - am70from email_split import email_split
email = email_split("ssss@ggh.com")
print(email.domain)
print(email.local)
以下代码将返回 @ 之前的连续文本
re.findall(r'(\S+)@', s)
import re
regex_email = r"([a-zA-Z0-9]+)@\S+"
s1 = "This is my email: hello@world.com"
print(re.findall(regex_email, s1))
#output is ['hello']
下面应该可以帮助您完成:
fromAddr = message.get('From').split('@')[1].rstrip('>')
fromAddr = fromAddr.split(' ')[0]
Tony Snow <tony@example.com>
和(tony snow) tony@example.com
?你想从tony%example.com@example.org
返回什么?当前电子邮件地址格式的标准在这里:http://www.rfc-editor.org/rfc/rfc5322.txt。 - Robᵩemail.utils.parseaddr
,或者在PyPI上搜索第三方库(如果某些原因不适用)。正确获取所有细节非常困难。这正是Python自带电池的原因。 - abarnert