2016-12-31 8 views
0

私はこのPythonコードを持っており、正規表現文字列の配列をコンパイルした正規表現にマップしたいので、特定のテキスト行が指定されたものと一致するかどうかを確認する関数を作成する必要があります正規表現。しかし、私はPythonを吸って、JSとJavaしか知りません。 JSで配列を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 

、私がしたいことは次のようになります。

// 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で配列のマッピングを行う方法を読んでいました。

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') 

出力:あなたはこのような何か試すことができます

答えて

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

これは私が持っているものである

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の答えを試しますが、ラムダ構文は私にはかなり外国です。

関連する問題