Python 字符串中的通配符搜索
- 2025-04-16 08:57:00
- admin 原创
- 20
问题描述:
假设我有一个列表
list = ['this','is','just','a','test']
我怎样才能让用户进行通配符搜索?
搜索词:'th_s'
将返回“this”
解决方案 1:
使用fnmatch
:
import fnmatch
lst = ['this','is','just','a','test']
filtered = fnmatch.filter(lst, 'th?s')
如果您想允许_
使用通配符,只需将所有下划线替换'?'
为(一个字符)或*
(多个字符)。
如果您希望用户使用更强大的过滤选项,请考虑允许他们使用正则表达式。
解决方案 2:
正则表达式可能是解决这个问题的最简单的方法:
import re
regex = re.compile('th.s')
l = ['this', 'is', 'just', 'a', 'test']
matches = [string for string in l if re.match(regex, string)]
解决方案 3:
你是指通配符的特定语法吗?通常*
代表“一个或多个”字符,并且?
代表“一个”。
最简单的方法可能是将通配符表达式转换为正则表达式,然后使用它来过滤结果。
解决方案 4:
与 Yuushi 使用正则表达式的想法相同,但它使用 re 库中的 findall 方法而不是列表推导:
import re
regex = re.compile('th.s')
l = ['this', 'is', 'just', 'a', 'test']
matches = re.findall(regex, string)
解决方案 5:
为什么不直接用 join 函数呢?在正则表达式 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 函数前面的单引号是放在列表每个字符串中间的内容。执行此代码部分 (' '.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)
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD