2016-04-24 32 views
0

我知道必須有做這一切的美好/更快的方法子 - 但我不得不野蠻的解決方案,現在的作品。這可以更有效地完成嗎?查找嵌入在特定的模式

的僞代碼:

zoneNAME='R::BBQ (ZP)_|_R::Family Room (ZP)_|_R::Firepit (ZP)_|_R::Kitchen (ZP)_|_R::Living Room_|_R::Media Room (ZP)_|_R::Portable (ZP)_|_R::Spa (ZP)_|_S::BBQ (ZP)_|_S::Family Room (ZP)_|_S::Firepit (ZP)_|_S::Kitchen (ZP)_|_S::Media Room (ZP)_|_S::Portable (ZP)_|_S::Spa (ZP)_|_' 
a = re.sub('_|_', '', zoneNAME) 
a = a.split('S::', 1)[0] 
a = re.sub('R::', '', a) 
a = re.split('\|', a) 
a = filter(None, a) 

最終輸出:

['BBQ (ZP)', 'Family Room (ZP)', 'Firepit (ZP)', 'Kitchen (ZP)', 'Living Room', 'Media Room (ZP)', 'Portable (ZP)', 'Spa (ZP)']

回答

1

您可以使用正回顧後發和正前瞻(見documentation):

> a = re.findall('(?<=R::).*?(?=_\|_)', zoneNAME) 

# '(?<=R::)x' -- positive lookbehind: matches 'x' that is preceded by 'R::' 
# 'x(?=_\|_)' -- positive lookahead: matches 'x' that is followed by '_|_' 
# .*? matches a sequence of any characters non-greedily 

> a 
> ['BBQ (ZP)', 'Family Room (ZP)', 'Firepit (ZP)', 'Kitchen (ZP)', 'Living Room', 
'Media Room (ZP)', 'Portable (ZP)', 'Spa (ZP)'] 

這返回所有先前子串的列表通過'R::' ED和隨後'_|_',並且這樣的字符串相匹配的非貪婪地,爲了不從第一'R::'匹配整個字符串的最後'_|_'

+0

這絕對是真棒 - 感謝。 – chow

0

試試這個代碼內置功能:

set(zoneNAME.replace('R::','').replace('S::','').split('_|_'))

相關問題