簡體   English   中英

提取連接字符串的特定部分

[英]Extract a specific portion of connection string

以任何方式提取@ (如果有)和next之前的內容. (如果有)?

例子:

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

我需要在變量中獲取host

用Python提出建議? 任何方法都歡迎。

謝謝,

編輯:我解決了我的問題。 也需要匹配hosthost.blah.blah

您可以使用幾個string.split調用,第一個使用“ @”作為分隔符,第二個使用“。”。

'@'分割,然后子串。

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

如果字符串中沒有@,則會拋出IndexError Exception異常。

'first.last@host.domain.com'.split('@')[1].split('.')[0]
host = re.search(r"@(\w+)(\.|$)", s).group(1)

這是另一種解決方案:

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

編輯:感謝評論更好的解決方案:

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)  

收益:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM