Another RegEx Question...

Gustavo Niemeyer niemeyer at conectiva.com
Mon Dec 13 11:30:38 EST 2004


Hello Andrea,

> I'm quite new to Python and I don't know if this is a FAQ (I
> can't find it) or an obvious question. I'm using the RE module
> in python, and I would like to be able to contruct something
> like the Window$ "Find Files Or Folders" engine. As the Window$
> users know, you can filter the file names using the character
> "*", as:
[...]

You're looking for the fnmatch module.

> import re
> mystring = "*yf*nam*"
> mystring.replace("*","\w+")
> php = re.compile(mystring + "\w+")
> 
> But it does not work...

  >>> re.compile("*yf*nam*".replace("*", ".*")+"$").match("myfilename")
  <_sre.SRE_Match object at 0xb7ab3b10>

> Is there a way to let the user of my application use the "*" character and
> to do a Regular Expression search inside a Python code?

  >>> import fnmatch
  >>> fnmatch.fnmatch("myfilename", "*yf*nam*")
  True
  >>> fnmatch.translate("*")
  '.*$'
  >>> fnmatch.translate("?yf*nam?")
  '.yf.*nam.$'

-- 
Gustavo Niemeyer
http://niemeyer.net



More information about the Python-list mailing list