Another RegEx Question...
Roel Schroeven
rschroev_nospam_ml at fastmail.fm
Mon Dec 13 08:21:39 EST 2004
andrea.gavana at agip.it wrote:
> Hello NG,
>
> 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)
>
> I have tried something like:
>
> import re
> mystring = "*yf*nam*"
> mystring.replace("*","\w+")
> php = re.compile(mystring + "\w+")
>
> But it does not work...
replace doesn't change the string in place (it can't, since strings are
immutable in Python); rather it returns a new string. You could, for
example, do something like
mystring = mystring.replace("*","\w+")
Note 1: I'm not sure of the meaning of '*' in Windows file wildcards,
but I think it would be more correct to translate it into '\w*' (i.e.
zero or more instead of one or more) or even '.*' (any character, not
only alphanumeric; will also match spaces etc. that might appear in
filenames).
Note 2: Instead of translating to regular expressions, it would probably
be easier to use the fnmatch and/or glob module. They use Unix
shell-style wildcards, which I believe are very similar to Windows style
wildcards, if not identical.
--
"Codito ergo sum"
Roel Schroeven
More information about the Python-list
mailing list