简体   繁体   中英

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 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.

您可以使用几个string.split调用,第一个使用“ @”作为分隔符,第二个使用“。”。

'@'分割,然后子串。

>>> 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]
host = re.search(r"@(\w+)(\.|$)", s).group(1)

Here is one more solution:

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

edit: Much better solution thanks to the comment:

re.search("@([^.]*)[.]?", str).group(1)
>>> s="first.last@host.domain.com"
>>> s[s.index("@")+1:]
'host.domain.com'
>>> s[s.index("@")+1:].split(".")[0]
'host'
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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM