如何在Python中的用户定义搜索字符串中支持通配符?

时间:2022-09-01 22:56:04

Is there a simple way to support wildcards ("*") when searching strings - without using RegEx?

搜索字符串时是否有一种简单的方法来支持通配符(“*”) - 不使用RegEx?

Users are supposed to enter search terms using wildcards, but should not have to deal with the complexity of RegEx:

用户应该使用通配符输入搜索条件,但不应该处理RegEx的复杂性:

"foo*"   =>  str.startswith("foo")
"*foo"   =>  str.endswith("foo")
"*foo*"  =>  "foo" in str

(it gets more complicated when there are multiple search terms though, e.g. "foobarbaz")

(当有多个搜索词时,它会变得更复杂,例如“foobarbaz”)

This seems like a common issue, so I wonder whether there's a ready-made solution for it.

这似乎是一个常见的问题,所以我想知道是否有一个现成的解决方案。

Any help would be greatly appreciated!

任何帮助将不胜感激!

1 个解决方案

#1


14  

You could try the fnmatch module, it's got a shell-like wildcard syntax.

你可以试试fnmatch模块,它有一个类似shell的通配符语法。

#1


14  

You could try the fnmatch module, it's got a shell-like wildcard syntax.

你可以试试fnmatch模块,它有一个类似shell的通配符语法。