开发者

Extract a specific portion of connection string

Any way to extract what's after the @(if any) and before the next . (if any)?

Examples:

host
host.domain.com
user@host
first.last@host
first.last@host.domain.com
first@host.domain.com

I need 开发者_StackOverflow中文版to get host in a variable.

Suggestions in Python? Any method is welcomed.

Thanks,

EDIT: I fixed my question. Need to match host and host.blah.blah too.


You can use a couple of string.split calls, the first using '@' as a separator, the second using '.'


>>> x = "first.last@host.domain.com"
>>> x.split("@")[1].split(".")[0]
'host'
>>> y = "first.last@host"
>>> y.split("@")[1].split(".")[0]
'host'
>>> 

There will be an IndexError Exception thrown if there is no @ in the string.


'first.last@host.domain.com'.split('@')[1].split('.')[0]


>>> s="first.last@host.domain.com"
>>> s[s.index("@")+1:]
'host.domain.com'
>>> s[s.index("@")+1:].split(".")[0]
'host'


host = re.search(r"@(\w+)(\.|$)", s).group(1)


import re

hosts = """
user@host1
first.last@host2
first.last@host3.domain.com
first@host4.domain.com
"""

print re.findall(r"@(\w+)", hosts)  

returns:

['host1', 'host2', 'host3', 'host4']


Here is one more solution:

re.search("^.*@([^.]*).*", str).group(1)

edit: Much better solution thanks to the comment:

re.search("@([^.]*)[.]?", str).group(1)


do a split by '@', and then substring.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜