Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中支持用户定义的搜索字符串中的*?_Python_Regex - Fatal编程技术网

如何在python中支持用户定义的搜索字符串中的*?

如何在python中支持用户定义的搜索字符串中的*?,python,regex,Python,Regex,此问题与此堆栈溢出问题相关: 但我只需要支持通配符,而不需要支持?或您通过fnmatch获得的[seq]功能。既然无法从fnmatch中删除该功能,那么还有其他方法吗 我需要这样一个用户定义的字符串:site.*.com/sub/ 要与此匹配:site.hostname.com/sub/ 没有所有的附加功能?和[]您可以使用split、re.escape和“^$”从搜索字符串编译regexp import re regex = re.compile('^' + '.*'.join(re.esc

此问题与此堆栈溢出问题相关:

但我只需要支持通配符,而不需要支持?或您通过fnmatch获得的[seq]功能。既然无法从fnmatch中删除该功能,那么还有其他方法吗

我需要这样一个用户定义的字符串:
site.*.com/sub/

要与此匹配:
site.hostname.com/sub/


没有所有的附加功能?和[]

您可以使用split、re.escape和“^$”从搜索字符串编译regexp

import re
regex = re.compile('^' + '.*'.join(re.escape(foo) for foo in pattern.split('*')) + '$')

您可以使用split、re.escape和“^$”从搜索字符串编译regexp

import re
regex = re.compile('^' + '.*'.join(re.escape(foo) for foo in pattern.split('*')) + '$')

如果它只有一个星号,并且您要求搜索字符串代表整个匹配字符串,则此操作有效:

searchstring = "site.*.com/sub/"
to_match = "site.hostname.com/sub/"

prefix, suffix = searchstring.split("*", 1)

if to_match.startswith(prefix) and to_match.endswith(suffix):
    print "Found a match!"

否则,构建一个类似regex的函数可能是最好的。

如果它只有一个星号,并且您需要搜索字符串来表示整个匹配字符串,那么这样做可以:

searchstring = "site.*.com/sub/"
to_match = "site.hostname.com/sub/"

prefix, suffix = searchstring.split("*", 1)

if to_match.startswith(prefix) and to_match.endswith(suffix):
    print "Found a match!"

否则,构建一个类似regex的函数可能是最好的。

这非常完美。我试图找出一种方法来逃避所有的稀土元素,但我认为这会非常复杂。这太完美了。我试图找出一种方法来逃避所有的re,但我认为这会非常复杂。是的,它是用户生成的,所以我可以成为任何东西。是的,它是用户生成的,所以我可以成为任何东西。