字符串中的Python通配符搜索


77

可以说我有一个清单

list = ['this','is','just','a','test']

如何让用户进行通配符搜索?

搜索词:“ th_s”

将返回“ this”

Answers:


55

正则表达式可能是解决此问题的最简单方法:

import re
regex = re.compile('th.s')
l = ['this', 'is', 'just', 'a', 'test']
matches = [string for string in l if re.match(regex, string)]

7
这不应该被接受(答案是regex不会处理通配符匹配)-例如,我正在寻找纯通配符解决方案(由@phihag提供),而我已经对regex很熟悉
jirislav

10
正则表达式如何不处理通配符匹配?
约翰·克特吉克

158

用途fnmatch

import fnmatch
lst = ['this','is','just','a','test']
filtered = fnmatch.filter(lst, 'th?s')

如果要允许_用作通配符,只需所有下划线替换'?'(一个字符)或*(多个字符)。

如果您希望用户使用功能更强大的过滤选项,请考虑允许他们使用正则表达式


1
:)很酷,但是我知道可以调整路径以匹配路径,如果存在斜线,它会不会很有趣?另外,它支持**通配符吗?(e->我已经检查过文档-它不会以不同的方式对待斜杠,因此**此处甚至不需要通配符)。
科斯2012年

该文档指出这fnmatch是“ Unix文件名模式匹配”。但是我只是尝试了一下,它似乎可以在Windows上运行。这是幸运的未定义行为,还是fnmatchWindows支持?
cowlinator

1
@cowlinator文件名匹配的方法称为Unix文件匹配,因为它起源于Unix,但与操作系统无关,就像阿拉伯数字在英语中一样。
phihag


2

您是说通配符的任何特定语法吗?通常*代表“一个或多个”字符,并?代表一个。

最简单的方法可能是将通配符表达式转换为正则表达式,然后将其用于过滤结果。


4
fnmatch模块具有将通配符匹配转换为正则表达式的功能:fnmatch.translate
Peter Wood

0

与Yuushi使用正则表达式的想法相同,但是它在re库中使用findall方法而不是列表理解:

import re
regex = re.compile('th.s')
l = ['this', 'is', 'just', 'a', 'test']
matches = re.findall(regex, string)

1
您仍然需要以某种方式从数组中获取字符串。
BartBiczBoży

0

您为什么不只使用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(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)

如果有单词“ th”和“ s”,此解决方案不会中断吗?(通过加入,您将获得“ th s”,并且将具有有效的匹配项。此外,如果列表中已经存在一个空格如“ this is”的字符串,则解决方案将返回“ this”事件,如果没有列表中的元素非常合适,这可能是一个问题。
FélixBrunet

@FélixBrunet,您绝对正确!我用循环编写了代码,避免了您提到的迭代!我相信自己的学习过程会有所改善。如果您要添加更多内容,请放心。谢谢。
米歇尔·苏亚雷斯

-6

简单的方法是尝试os.system

import os
text = 'this is text'
os.system("echo %s | grep 't*'" % text)

10
所以...如果我把text =“ die | rm -rf /”会怎样?
WoLfulus

两个问题。首先,您无需执行python即可完成的功能。其次,并非所有操作系统都具有grep。
克莱尔·威廉姆森
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.