Search code examples
pythonwildcard

Wildcard before and after search


I'm working on a project that searches for filenames that match a string. The current working code appends an * to the end of the string and the code properly takes the string and matches it when there's a file extension and/or a number after, that works right. I'm wanting it to ignore things before the initial string as well to check the interior of the file name. For example File A File B.txt will be found by a string search for File A "or File B

Working code:

redeemed = redeemed + "*"
results = [file for file in sounds if re.search(redeemed, file)]

Non-working code:

redeemed = "*" + redeemed + "*"
results = [file for file in sounds if re.search(redeemed, file)]

Returns error:

Task exception was never retrieved
future: <Task finished name='Task-19' coro=<PubSub.__handle_message() done, defined at C:\Users\dmvh1\AppData\Local\Programs\Python\Python310\lib\site-packages\twitchAPI\pubsub.py:293> exception=error('nothing to repeat at position 0')>
Traceback (most recent call last):
  File "C:\Users\username\AppData\Local\Programs\Python\Python310\lib\site-packages\twitchAPI\pubsub.py", line 298, in __handle_message
    sub(uuid, msg_data)
  File "C:\Users\username\Desktop\TwitchSounds\InProgress.py", line 34, in callback_redemptions
    results = [file for file in sounds if re.search(redeemed, file)]
  File "C:\Users\username\Desktop\TwitchSounds\InProgress.py", line 34, in <listcomp>
    results = [file for file in sounds if re.search(redeemed, file)]
  File "C:\Users\username\AppData\Local\Programs\Python\Python310\lib\re.py", line 200, in search
    return _compile(pattern, flags).search(string)
  File "C:\Users\username\AppData\Local\Programs\Python\Python310\lib\re.py", line 303, in _compile
    p = sre_compile.compile(pattern, flags)
  File "C:\Users\username\AppData\Local\Programs\Python\Python310\lib\sre_compile.py", line 788, in compile
    p = sre_parse.parse(p, flags)
  File "C:\Users\username\AppData\Local\Programs\Python\Python310\lib\sre_parse.py", line 955, in parse
    p = _parse_sub(source, state, flags & SRE_FLAG_VERBOSE, 0)
  File "C:\Users\username\AppData\Local\Programs\Python\Python310\lib\sre_parse.py", line 444, in _parse_sub
    itemsappend(_parse(source, state, verbose, nested + 1,
  File "C:\Users\username\AppData\Local\Programs\Python\Python310\lib\sre_parse.py", line 669, in _parse
    raise source.error("nothing to repeat",
re.error: nothing to repeat at position 0

We were concerned the code with redeemed would catch EVERYTHING, but instead it catches nothing. Any ideas on how to implement this search?


Solution

  • If it's just a plain text search, you don't need regex or glob:

    results = [file for file in sounds if redeemed in file]
    

    No * or .* needed