Another RegEx Question...

Fredrik Lundh fredrik at pythonware.com
Mon Dec 13 17:30:26 CET 2004


<andrea.gavana at agip.it> wrote:

>      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:
>
> myfilen*                 (Will find a file named myfilenames)
> *yf*nam*                (Will find a file named myfilenames)

in Unix lingo, that's known as a "glob" pattern.  it's not really a regular
expression.

if you insist on using regular expressions, you can use the fnmatch.translate
function to convert from pattern to expression:

    >>> import fnmatch
    >>> fnmatch.translate("myfilen*")
    'myfilen.*$'
    >>> fnmatch.translate("*yf*nam*")
    '.*yf.*nam.*$'

or you can use fnmatch.filter() to find matching names in a list:

    >>> fnmatch.filter(["hello.txt", "bye.txt", "spam.egg"], "*.txt")
    ['hello.txt', 'bye.txt']

but it's likely that what you really want is the "glob" module, which looks
for files matching a given pattern:

    >>> import glob
    >>> glob.glob("*.txt")
    ['key.txt', 'some_document.txt']

more info here:

    http://docs.python.org/lib/module-glob.html
    http://docs.python.org/lib/module-fnmatch.html

</F> 






More information about the Python-list mailing list