让我们说我有一个清单
list = ['this','is','just','a','test']
Run Code Online (Sandbox Code Playgroud)
如何让用户进行通配符搜索?
搜索词:'th_s'
会回来'这个'
phi*_*hag 140
用途fnmatch:
import fnmatch
lst = ['this','is','just','a','test']
filtered = fnmatch.filter(lst, 'th?s')
Run Code Online (Sandbox Code Playgroud)
如果要允许_作为通配符,只需用(对于一个字符)或(对于多个字符)替换所有下划线.'?'*
如果您希望用户使用更强大的过滤选项,请考虑允许他们使用正则表达式.
Yuu*_*shi 51
正则表达式可能是解决此问题的最简单方法:
import re
regex = re.compile('th.s')
l = ['this', 'is', 'just', 'a', 'test']
matches = [string for string in l if re.match(regex, string)]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
209731 次 |
| 最近记录: |