![](/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.