2015-12-06 10 views
7

正規表現を使用してPythonで文字列のリストをフィルタリングしたいと思います。次の場合は、ファイルの拡張子を「.npy」にしてください。リスト内の正規表現による文字列のフィルタリング

import re 

files = [ '/a/b/c/la_seg_x005_y003.png', 
      '/a/b/c/la_seg_x005_y003.npy', 
      '/a/b/c/la_seg_x004_y003.png', 
      '/a/b/c/la_seg_x004_y003.npy', 
      '/a/b/c/la_seg_x003_y003.png', 
      '/a/b/c/la_seg_x003_y003.npy', ] 

regex = re.compile(r'_x\d+_y\d+\.npy') 

selected_files = filter(regex.match, files) 
print(selected_files) 

同じ正規表現はRubyで私の作品:動作しません

コードが

selected = files.select { |f| f =~ /_x\d+_y\d+\.npy/ } 

Pythonコードと何が問題なのですか?

+1

あなたはnは 'files 'の要素を' .npy'拡張子でフィルタリングしますか? –

答えて

14
selected_files = filter(regex.match, files) 

re.match('regex')re.search('^regex')またはtext.startswith('regex')に等しいが、正規表現のバージョンです。 文字列が正規表現で始まるかどうかをチェックするだけです。

ので、代わりにre.search()を使用します。

import re 

files = [ '/a/b/c/la_seg_x005_y003.png', 
      '/a/b/c/la_seg_x005_y003.npy', 
      '/a/b/c/la_seg_x004_y003.png', 
      '/a/b/c/la_seg_x004_y003.npy', 
      '/a/b/c/la_seg_x003_y003.png', 
      '/a/b/c/la_seg_x003_y003.npy', ] 

regex = re.compile(r'_x\d+_y\d+\.npy') 

selected_files = filter(regex.search, files) 
print(selected_files) 

出力:あなただけ.npyのすべてのファイルを取得したい場合

['/a/b/c/la_seg_x005_y003.npy', 
'/a/b/c/la_seg_x004_y003.npy', 
'/a/b/c/la_seg_x003_y003.npy'] 

そして、ちょうど使用str.endswith()

files = [ '/a/b/c/la_seg_x005_y003.png', 
      '/a/b/c/la_seg_x005_y003.npy', 
      '/a/b/c/la_seg_x004_y003.png', 
      '/a/b/c/la_seg_x004_y003.npy', 
      '/a/b/c/la_seg_x003_y003.png', 
      '/a/b/c/la_seg_x003_y003.npy', ] 


selected_files = filter(lambda x: x.endswith('.npy'), files) 

print(selected_files) 
+0

'filter()'が 're.search()'メソッドを受け入れるのはなぜですか?なぜなら、後者は 'MatchObject'のインスタンスを返すのでブール値ではないからです。これは16.8.3の[here](http://www.diveintopython.net/functional_programming/filtering_lists.html)で説明されています: 'search()' - メソッドは、項目が一致し、 'filter()'が解釈するとMatchObjectを返しますそれは真実です。それ以外の場合、 'search()'はNoneを返します。これはFalseと解釈されます。 – user3469861

3

search - 文字列の先頭から末尾(つまり全体)の一致が開始され、文字列内の任意の場所に一致する検索が開始されます。

import re 

files = [ '/a/b/c/la_seg_x005_y003.png', 
      '/a/b/c/la_seg_x005_y003.npy', 
      '/a/b/c/la_seg_x004_y003.png', 
      '/a/b/c/la_seg_x004_y003.npy', 
      '/a/b/c/la_seg_x003_y003.png', 
      '/a/b/c/la_seg_x003_y003.npy', ] 

regex = re.compile(r'_x\d+_y\d+\.npy') 

selected_files = filter(regex.search, files) 
print(selected_files) 

出力 -

['/a/b/c/la_seg_x005_y003.npy', '/a/b/c/la_seg_x004_y003.npy', '/a/b/c/la_seg_x003_y003.npy'] 
1

あなたmatch場合、パターンは全体入力をカバーしなければなりません。 あなたの正規表現拡張次のいずれかと一致します

regex = re.compile(r'.*_x\d+_y\d+\.npy') 

['/a/b/c/la_seg_x005_y003.npy', 
'/a/b/c/la_seg_x004_y003.npy', 
'/a/b/c/la_seg_x003_y003.npy'] 

または文字列による

スキャンがどこ正規表現最初の場所を探してre.searchを使用しますパターンは一致を生成する[...]

1

re.match()は、文字列の先頭に一致するものがあるかどうかを調べます。代わりにre.search()を使用できます。