Home > Software design >  Finding file name using regex from glob
Finding file name using regex from glob

Time:04-29

I have directory with files as follows.

  • test.[8 random alphanumeric characters].js
  • test.[8 random alphanumeric characters].[10 random alphanumeric characters].js

I want to find the file test.[8 random alphanumeric characters].js using glob.

When do the following it returns both files.

from glob import glob

glob(BASEDIR   '/test.*.js')

and when I do the following it returns an empty array.

from glob import glob

glob(BASEDIR   '/test.[a-zA-Z0-9]{8}.js')

What am I doing wrong?

CodePudding user response:

regex solution:

import os
import re
res=[i for i in os.listdir(BASEDIR) if re.match(r'test\.[a-zA-Z0-9]{8}\.js',i)]
print(res)

NOTE: the solution would just be the name of file, you can use

os.join(BASEDIR,res[i])

to get full path

  • Related