2017-04-01 72 views
0

我的問題涉及以下數據列表。如何選擇特定地點上的特定字符

data = ['TNNI3', 'TSHZ3/THEG5', 'ACTR3BP2-', 'BIN1/CYP27C1', 
'-', 'NBPF1/NBPF20', 'ERBB4', '-NBPF20', '-'] 

只有與其他東西結合時,我需要選擇字符「 - 」。如果它自己支持,它需要保持未選中狀態。

例如,需要選擇'ACTR3BP2-'和'-NBPF20'中的「 - 」,並且列表中的兩個' - '需要保持未選中狀態。

有誰知道如何通過在python3中使用正則表達式?

一旦選擇了正確的「 - 」,我想從列表中刪除它們。 我怎麼想這樣做是使用re.sub函數並將其替換爲一個空白空間。如果有人有更好的想法做到這一點。我很高興聽到他們!

+0

是否要刪除'-'元素? ['[x for x in x!=' - ']'](http://ideone.com/Y16Ihf)?或者只是提取那些包含'-'但不等於它的元素 - ['[x在x和x!'中爲'x'的數據x'=' - ']'](http://ideone.com/Lvs4Hs )? –

+0

請參閱我對Python 3正則表達式解決方案的回答。 – ferit

回答

-1
(?:(-)([\d\w]{1,})|([\d\w]{1,})(-)) captures as you wish. 

演示在這裏:https://regex101.com/r/IJMPDX/3

和替代是這樣的:

4捕獲的連字符,第二和第三的內容的其餘各組,第一和第四。我們捕獲4組,然後只拿第二和第三,以消除連字符組。

regex = r"(?:(-)([\d\w]{1,})|([\d\w]{1,})(-))" 

test_str = ("-1wdq32e2\n" 
    "2123sdasa-\n" 
    "ACTR3BP2-\n" 
    "-NBPF20\n") 

subst = "\\2\\3" # Captured 4 groups, taking only 2nd and 3rd 

# You can manually specify the number of replacements by changing the 4th argument 
result = re.sub(regex, subst, test_str, 0) 

if result: 
    print (result) 

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution. 
0

如果你不需要正則表達式,有一個更好的方法來做到這一點。做一個字符串比較和替換會比使用Regex更快。

import re 

data = ['TNNI3', 'TSHZ3/THEG5', 'ACTR3BP2-', 'BIN1/CYP27C1', 
     '-', 'NBPF1/NBPF20', 'ERBB4', '-NBPF20', '-'] 

for e in data: 
    if "-" in e and e != "-": 
     old = e 
     new = e.replace("-", "") 
     print(old + " >> " + new)