Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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):
        # ...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading