2017-07-26 39 views
-4

我有這樣一個字符串列表:正則表達式的多個字符串匹配

["ra", "dec", "ra-error", "dec-error", "glat", "glon", "flux", "l", "b"]

我需要找到在此列表中包含"ra""dec""lat"

所有字符串我檢查了許多其他線程以及正則表達式手冊。結果對我來說太困惑了。請求幫助。 :(

+1

你不需要這個正則表達式。 –

回答

3

你不需要正則表達式這在所有。與any列表理解就足夠了

>>> subs = ['ra', 'dec', 'lat'] 
>>> strings = ["ra", "dec", "ra-error", "dec-error", "glat", "glon", "flux", "l", "b"] 
>>> [s for s in strings if any(i in s for i in subs)] 
['ra', 'dec', 'ra-error', 'dec-error', 'glat'] 
0

下面是使用正則表達式的一個解決方案,如果這就是你真正需要的。我搜索,看看是否有任何你的3子存在列表中的任何給定的字符串中。使用https://docs.python.org/3/library/re.html爲Python的正則表達式庫。

import re 
for word in wordList: 
    m = re.search('.*(ra|dec|lat).*', word) 
    if m: 
    <youve matched here> 
0

find也適用於您的問題。

a=["ra", "dec", "ra-error", "dec-error", "glat", "glon", "flux", "l", "b"] 
b=[] 
for i in a: 
    if i.find("ra")!=-1: 
     b.append(i) 
    if i.find("dec")!=-1: 
     b.append(i) 
    if i.find("lat")!=-1: 
     b.append(i) 
print b 

b=['ra', 'dec', 'ra-error', 'dec-error', 'glat'] 
相關問題