-1

I want to capture with regex all the files in a folder that contain for example the string "key1" but I don't want to capture the files that have another character after that.

Let's say in the folder there are three files:

  • key1.txt
  • key12.txt
  • xykey1.txt

When I execute my code, I would like only the first and third file to show.

This is the code I have:

import os
import re

dest = "C:\Work\Python\Files"

for root, dirs, files in os.walk(dest):
    for file in files:
        if re.findall("key1", file, re.IGNORECASE):
            print(file)

With my current code, all three files are caught.

Can someone give me a hint on how not to get "key12" but only the files which contain "key1"?

falco
  • 143
  • 1
  • 2
  • 13
  • 1
    Use a digit boundary, `r"key1(?!\d)"` – Wiktor Stribiżew May 17 '22 at 12:45
  • The link does not have an answer to this specific case, and this question OP is asking does not really require regex. Removing the suffix and using `endswith("key1")` should suffice for this purpose. – PIG208 May 17 '22 at 12:50
  • @PIG208 : true, but if there were any other file like for example "abckey1fggg.txt" - then the regex works better. – falco May 17 '22 at 13:06

0 Answers0