我正在做一个搜索与字符串匹配的文件名的项目。当前的工作代码在字符串的末尾附加一个*
,当后面有文件扩展名和/或数字时,代码会正确地获取字符串并匹配它,这是正确的。我希望它忽略初始字符串之前的内容,并检查文件名的内部。例如CCD_ 2将通过对CCD_;或File B
工作代码:
redeemed = redeemed + "*"
results = [file for file in sounds if re.search(redeemed, file)]
非工作代码:
redeemed = "*" + redeemed + "*"
results = [file for file in sounds if re.search(redeemed, file)]
返回错误:
Task exception was never retrieved
future: <Task finished name='Task-19' coro=<PubSub.__handle_message() done, defined at C:Usersdmvh1AppDataLocalProgramsPythonPython310libsite-packagestwitchAPIpubsub.py:293> exception=error('nothing to repeat at position 0')>
Traceback (most recent call last):
File "C:UsersusernameAppDataLocalProgramsPythonPython310libsite-packagestwitchAPIpubsub.py", line 298, in __handle_message
sub(uuid, msg_data)
File "C:UsersusernameDesktopTwitchSoundsInProgress.py", line 34, in callback_redemptions
results = [file for file in sounds if re.search(redeemed, file)]
File "C:UsersusernameDesktopTwitchSoundsInProgress.py", line 34, in <listcomp>
results = [file for file in sounds if re.search(redeemed, file)]
File "C:UsersusernameAppDataLocalProgramsPythonPython310libre.py", line 200, in search
return _compile(pattern, flags).search(string)
File "C:UsersusernameAppDataLocalProgramsPythonPython310libre.py", line 303, in _compile
p = sre_compile.compile(pattern, flags)
File "C:UsersusernameAppDataLocalProgramsPythonPython310libsre_compile.py", line 788, in compile
p = sre_parse.parse(p, flags)
File "C:UsersusernameAppDataLocalProgramsPythonPython310libsre_parse.py", line 955, in parse
p = _parse_sub(source, state, flags & SRE_FLAG_VERBOSE, 0)
File "C:UsersusernameAppDataLocalProgramsPythonPython310libsre_parse.py", line 444, in _parse_sub
itemsappend(_parse(source, state, verbose, nested + 1,
File "C:UsersusernameAppDataLocalProgramsPythonPython310libsre_parse.py", line 669, in _parse
raise source.error("nothing to repeat",
re.error: nothing to repeat at position 0
我们担心被赎回的代码会捕获所有东西,但它什么也没捕获。关于如何实现此搜索,有什么想法吗?
如果只是纯文本搜索,则不需要regex或glob:
results = [file for file in sounds if redeemed in file]
无需*
或.*
如果文件名是作为字符串处理的,那么就不必使用anyString+*
只需在字符串中搜索您想要查找的内容
如果我的来源是正确的,pythonsearch()
将为你完成任务"search((函数如果在字符串中找到模式的匹配项,则返回Match对象。。。。search((匹配字符串"中的任何位置;
像这个
results = [file for file in sounds if re.search(redeemed, file)]