![](/img/trans.png)
[英]How to remove parts of a string that comes after a 'general pattern' using Python
[英]python split a string when a keyword comes after a pattern
我有一个主机名
ab-test-db-dev.0002-colo1-vm234.abc.domain.com
(是的,主机名内部没有遵循任何约定。)
我试图将此主机名拆分为
ab-test-db-dev.0002-colo1-vm234
模式是用 '.' 分割,但前提是该点后面没有其他特殊字符。
我试过
pattern = domain.split(".")
但它只需要直到
ab-test-db-dev and not ab-test-db-dev.0002-colo1-vm234
作为第一个元素。
实现这一目标的最佳方法是什么?
您可以删除第一部分,直到不再有破折号; 这将是要从主机名中删除的域名:
hostname = domain
while '-' in domain:
domain = domain.partition('.')[-1]
hostname = hostname[:-len(domain) - 1]
或者str.rpartition()
,如果最后一部分不包含破折号,则使用str.rpartition()
删除它:
hostname = domain
while True:
first, _, end = hostname.rpartition('.')
if '-' in end:
break
hostname = first
使用正则表达式查找仅包含字母和点的任何部分:
import re
hostname = re.sub(r'\.[a-z.]+$', '', domain)
演示:
>>> domain = 'ab-test-db-dev.0002-colo1-vm234.abc.domain.com'
>>> hostname = domain
>>> while '-' in domain:
... domain = domain.partition('.')[-1]
...
>>> hostname[:-len(domain) - 1]
'ab-test-db-dev.0002-colo1-vm234'
>>> domain = 'ab-test-db-dev.0002-colo1-vm234.abc.domain.com'
>>> hostname = domain
>>> while True:
... first, _, end = hostname.rpartition('.')
... if '-' in end:
... break
... hostname = first
...
>>> hostname
'ab-test-db-dev.0002-colo1-vm234'
>>> import re
>>> re.sub(r'\.[a-z.]+$', '', domain)
'ab-test-db-dev.0002-colo1-vm234'
没有得到模式,但对于这种情况,以下可以工作。
(?<=\d)\.
尝试这个:
https://regex101.com/r/rU8yP6/21
使用re.split
。
import re
re.split(r"(?<=\d)\.",test_Str)
或者
^(.*?)(?!.*-)\.
尝试这个:
https://regex101.com/r/rU8yP6/22
import re
print re.findall(r"^(.*?)(?!.*-)\.",test_str)
如果我正确理解你的问题,那么这个正则表达式应该可以完成这项工作:
.*?(?=\\.(?!.*[^\\w.]))
>>> print re.match(r'.*?(?=\.(?!.*[^\w.]))', 'ab-test-db-dev.0002-colo1-vm234.abc.domain.com')
ab-test-db-dev.0002-colo1-vm234
解释:
.*? # match everything up to...
(?=
\. # the first dot...
(?! # that isn't followed by...
.* # any text and...
[^\w.] # something that's not a word character or a dot.
)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.