Home > Blockchain >  How can I use regex to select filenames that contain a certain string?
How can I use regex to select filenames that contain a certain string?

Time:12-05

I need to iterate over files and select those that end with _FirstPerson_04312.json or _Hybrid_04312.json, where 04312 can be any sequence of digits 0-9. I haven't used regex much so far, can someone help me how to do this? Thanks!

my code so far:

for fname in os.listdir(path=search_path):
   if fname.endswith(".json"):
      # if fname contains -- regex

CodePudding user response:

You can match both json ending and number pattern in one go with the re package:

import re

for fname in os.listdir(path=search_path):
    if re.match(".*?_(?:FirstPerson|Hybrid)_\d .json", fname):
        # ...

CodePudding user response:

You can fairly easy check the regex with https://regex101.com

import re

result = []

files = ["ffdf_FirstPerson_04312.json", "ffff_Hybrid_04312.json", "ajaxamsterdam.json"]
for fname in files:
    if fname.endswith(".json"):
        x = re.findall('_FirstPerson_\d*.json|_Hybrid_\d*.json', fname)
        if x:
            result.append(fname)
  • Related