2016-12-31 50 views
0

我有這個Python代碼,我想映射正則表達式字符串數組,以編譯正則表達式,並且我需要創建一個函數,檢查是否某行文本匹配所有給定的常用表達。但我吮吸Python,只知道JS和Java。如何使用Python映射數組

#sys.argv[2] is a JSON stringified array 

regexes = json.loads(sys.argv[2]); 

#need to call this for each regex in regexes 
pattern = re.compile(regex) 

def matchesAll(line): 
    return True if all line of text matches all regular expressions 

在JS,我想是這樣的:

// process.argv[2] is a JSON stringified array 
var regexes = JSON.parse(process.argv[2]) 
       .map(v => new RegExp(v)) 

function matchesAll(line){ 
    return regexes.every(r => r.test(line)); 
} 

可以以某種方式幫我翻譯?我正在閱讀有關如何使用Python進行數組映射的問題,我就像是吧?

回答

2

編譯所有表達式,你可以簡單地使用

patterns = map(re.compile, regexs) 

,並做了檢查:

def matchesAll(line): 
    return all(re.match(x, line) for x in patterns) 
+0

答案謝謝,幫助很多 –

+0

更多Pythonic +1 – MYGz

+0

我必須「導入所有」嗎? –

1

你可以嘗試這樣的事情:

regexes = [re.compile(x) for x in json.loads(sys.argv[2])] 

def matchesAll(line): 
    return all([re.match(x, line) for x in regexes]) 

測試例:

import re 

regexes = [re.compile(x) for x in ['.*?a.*','.*?o.*','.*r?.*']] 

def matchesAll(line): 
    return all([re.match(x, line) for x in regexes]) 

print matchesAll('Hello World aaa') 
print matchesAll('aaaaaaa') 

輸出:

True 
False 
+0

感謝,我會移動到這一點,我會後的我有什麼 –

0

這是我有什麼,我希望這是正確的

regex = json.loads(sys.argv[2]); 

regexes=[] 

for r in regex: 
    regexes.append(re.compile(r)) 

def matchesAll(line): 
    for r in regexes: 
     if not r.search(line): 
      return False 
    return True 

我會試試@ MYGz的答案,lambda語法對我來說很陌生。