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

时间:2022-09-13 11:24:37

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.

建议在Python中?任何方法都受到欢迎。

Thanks,

谢谢,

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

编辑:我回答了我的问题。需要匹配主机和主机。废话了。

8 个解决方案

#1


1  

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

如果字符串中没有@,就会抛出IndexError异常。

#2


1  

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

您可以使用几个字符串。拆分调用,第一个使用“@”作为分隔符,第二个使用“。”

#3


1  

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

#4


0  

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

#5


0  

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

#6


0  

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']

#7


0  

Here is one more solution:

这里还有一个解决方案:

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

edit: Much better solution thanks to the comment:

编辑:由于评论,更好的解决方案:

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

#8


0  

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

用“@”来拆分,然后用子字符串。

#1


1  

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

如果字符串中没有@,就会抛出IndexError异常。

#2


1  

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

您可以使用几个字符串。拆分调用,第一个使用“@”作为分隔符,第二个使用“。”

#3


1  

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

#4


0  

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

#5


0  

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

#6


0  

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']

#7


0  

Here is one more solution:

这里还有一个解决方案:

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

edit: Much better solution thanks to the comment:

编辑:由于评论,更好的解决方案:

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

#8


0  

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

用“@”来拆分,然后用子字符串。