2016-12-31 55 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语法对我来说很陌生。