2017-05-30 4 views
0

Regexを使用して、一連の単語をPythonで完全に一致させたいと思います。 静的には可能ですが、動的なマッチングの仕方についてはわかりません。RegexをPythonで動的に使用する方法

staticメソッド

import re 
print(re.search(r'\bsmaller than or equal\b', 'When the loan amount is smaller than or equal to 50000')) 

私はリストでシーケンス全体を照合することによって、動的に同じことをやろうとしています。ここ
は、以下のコードの断片である:

import re 
list_less_than_or_equal = ['less than or equal', 'lesser than or equal', 'lower than or equal', 'smaller than or equal','less than or equals', 'lesser than or equals', 'lower than or equals', 'smaller than or equals', 'less than equal', 'lesser than equal', 'higher than equal','less than equals', 'lesser than equals', 'higher than equals'] 

for word in list_less_than_or_equal: 
    print(re.search(r'\b'+word+'\b', 'When the loan amount is smaller than or equal to 50000')) 

これは出力としてNone印刷します。

単語のシーケンス全体を動的に照合するにはどうすればよいですか?

答えて

4

を忘れました'\b'

re.search(r'\b' + re.escape(word) + r'\b', ...) 
#         ^

escape sequence \bはPythonで特別な意味を持っており、\x08(U + 0008)になります。 \x08を見ている正規表現エンジンは、このリテラル文字と一致するように試み、失敗します。

また、私はre.escape(word)を使用して特別な正規表現をエスケープしました。単語が"etc. and more"の場合、ドットは任意の文字と一致するのではなく文字通りにマッチします。

+0

あなたの方法論は正しいですが、re.quoteは、属性のエラーが発生します。 – User456898

+1

申し訳ありませんが、 're.escape'である必要があります。更新しました。 – kennytm

+0

それは今適切です。 – User456898

2

連結を使用する代わりに、format文字列を使用できます。

re.search(r'\b{0}\b'.format(word), ....) 
+0

あなたのメソッドは正常に動作します。 – User456898

1

代替方法がオプションであれば、あなたはリストにリストを比較することができます:

list_less_than_or_equal = ['less than or equal', 'lesser than or equal', 'lower than or equal', 'smaller than or equal','less than or equals', 'lesser than or equals', 'lower than or equals', 'smaller than or equals', 'less than equal', 'lesser than equal', 'higher than equal','less than equals', 'lesser than equals', 'higher than equals'] 

if any(word in 'When the loan amount is smaller than or equal to 50000' for word in list_less_than_or_equal): 
    print("yep"); 
else: 
    print("nope"); 

または正規表現を:

import re 

list_less_than_or_equal = ['less than or equal', 'lesser than or equal', 'lower than or equal', 'smaller than or equal','less than or equals', 'lesser than or equals', 'lower than or equals', 'smaller than or equals', 'less than equal', 'lesser than equal', 'higher than equal','less than equals', 'lesser than equals', 'higher than equals'] 

if any(re.findall(r'|'.join(list_less_than_or_equal), 'When the loan amount is smaller than or equal to 50000', re.IGNORECASE)): 
    print ('yep') 
else: 
    print ('nope') 
+0

それは動作しますが、Regexが欲しかったです。 – User456898

+1

@ User456898私は編集をしました。多分助けてください。ありがとう –

+0

あなたの答えは非常に良いですが、残念ながら1つの答えだけが目盛りに選択することができます。 – User456898

関連する問題