glob & fnmatch unable to match dirs/files containing [ ] ?

John Machin sjmachin at lexicon.net
Sat Mar 22 19:46:01 EST 2003


On Sat, 22 Mar 2003 18:33:45 -0500, Peter Hansen <peter at engcorp.com>
wrote:

>Steven Taschuk wrote:
>> 
>> Quoth Robert:
>>   [...]
>> > quoting attempts don't work:
>> >
>> > >>> glob.glob(  r'testsync\[2\]/*'  )            # or  'testsync\\[2\\]/*'
>> > []
>> 
>> You can quote the '[' by putting it in a character class of its
>> own:
>>         >>> glob.glob('testsync[[]2]')
>>         ['testsync[2]']
>
>I'm not certain, but I believe you would need
>to change the order to  'testsync[][2]'

Attaining certainty is not very bothersome:
>>> fnmatch.fnmatch("foo[2]bar", "foo[][2]bar")
0

> ... this
>looks like an empty class then one with a single 2
>in it, but it's not. 

Oh yes it is.
>>> fnmatch.fnmatch("foo2bar", "foo[][2]bar")
1

> Yours would look like a single
> [ in a class, then a 2 and then... syntax error or
>something,

Please try some examples and/or look at the source instead of just
guessing.

> since you've got a closing ] without a 
>matching opening one.

which is *not* a syntax error; ] is a meta-character only in the
context of an earlier unmatched [





More information about the Python-list mailing list