[英]Split a string in Python with ) and space after
我有一個像這樣的字符串:
'srv1(compA1 compA2) srv2(compA3 compA2) srv3(comp4 comp5)'
我需要這樣分割它:
['srv1(compA1 compA2)', 'srv2(compA3 compA2)', 'srv3(comp4 comp5)' ]
我試圖按空間拆分它,但它拆分了comp1 comp2的內部字符串...
In [9]: import re
In [10]: string = 'srv1(compA1 compA2) srv2(compA3 compA2) srv3(comp4 comp5)'
In [11]: re.split(r'(?<=\)) ', string)
Out[11]: ['srv1(compA1 compA2)', 'srv2(compA3 compA2)', 'srv3(comp4 comp5)']
只需您可以嘗試這種方式
a='srv1(compA1 compA2) srv2(compA3 compA2) srv3(comp4 comp5)'
print a.replace(' s','###s').split('###')
#output
['srv1(compA1 compA2)', 'srv2(compA3 compA2)', 'srv3(comp4 comp5)']
或者你可以使用regular expression
您可以分割')',然后像這樣將')'添加回去:
line = 'srv1(compA1 compA2) srv2(compA3 compA2) srv3(comp4 comp5)'
[e if e.endswith(')') else e + ')' for e in line.split(') ')]
['srv1(compA1 compA2)', 'srv2(compA3 compA2)', 'srv3(comp4 comp5)']
有點難看,但是可以用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.