私がリストを持っているとしましょう
list = ['this','is','just','a','test']
ユーザーにワイルドカード検索を実行させるにはどうすればよいですか?
検索ワード:'th_s'
'this'を返します
私がリストを持っているとしましょう
list = ['this','is','just','a','test']
ユーザーにワイルドカード検索を実行させるにはどうすればよいですか?
検索ワード:'th_s'
'this'を返します
正規表現は、おそらくこの問題の最も簡単な解決策です。
import re
regex = re.compile('th.s')
l = ['this', 'is', 'just', 'a', 'test']
matches = [string for string in l if re.match(regex, string)]
ワイルドカードの特定の構文を意味しますか?通常*
、「1つまたは複数の」文字を?
表し、1つを表します。
最も簡単な方法は、ワイルドカード式を正規表現に変換し、それを使用して結果をフィルタリングすることです。
正規表現を使用するという点でYuushiと同じ考えですが、これはリスト内包表記の代わりにreライブラリ内のfindallメソッドを使用します。
import re
regex = re.compile('th.s')
l = ['this', 'is', 'just', 'a', 'test']
matches = re.findall(regex, string)
結合機能だけを使ってみませんか?正規表現のfindall()またはgroup()では、文字列が必要になるため、次のようになります。
import re
regex = re.compile('th.s')
l = ['this', 'is', 'just', 'a', 'test']
matches = re.findall(regex, ' '.join(l)) #Syntax option 1
matches = regex.findall(' '.join(l)) #Syntax option 2
join()関数を使用すると、リストを文字列に変換できます。結合前の一重引用符は、リストの各文字列の中央に配置するものです。このコード部分('' .join(l))を実行すると、次のようになります。
「これは単なるテストです」
したがって、findal()関数を使用できます。
私は7年遅れていることは知っていますが、勉強していて他の人も同じ質問をする可能性があるため、最近アカウントを作成しました。これがあなたや他の人の助けになることを願っています。
@FélixBrunetコメント後の更新:
import re
regex = re.compile(r'th.s')
l = ['this', 'is', 'just', 'a', 'test','th','s', 'this is']
matches2=[] #declare a list
for i in range(len(l)): #loop with the iterations = list l lenght. This avoid the first item commented by @Felix
if regex.findall(l[i]) != []: #if the position i is not an empty list do the next line. PS: remember regex.findall() command return a list.
if l[i]== ''.join(regex.findall(l[i])): # If the string of i position of l list = command findall() i position so it'll allow the program do the next line - this avoid the second item commented by @Félix
matches2.append(''.join(regex.findall(l[i]))) #adds in the list just the string in the matches2 list
print(matches2)
簡単な方法は試してみてくださいos.system
:
import os
text = 'this is text'
os.system("echo %s | grep 't*'" % text)