0

I am using Python 3.7.6 and the fnmatch.fnmatch function to match a filename with a given pattern. Most of my tests worked, but in specific the following example doesn't return the value as expected. Give is the following exanoke:

> fnmatch.fnmatch('_foo\bar.exe', '^_*')
False

What I try to do, to match any filename whose component starts with _. Any help is highly appreciated

HelloWorld
  • 2,392
  • 3
  • 31
  • 68
  • What leads you to think that `^` matches leading characters in a *glob* expression, as opposed to a regex? – Charles Duffy Feb 20 '20 at 18:59
  • See the POSIX `fnmatch` spec at https://pubs.opengroup.org/onlinepubs/9699919799/functions/fnmatch.html, and the glob syntax it includes by reference at https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_13_02 -- `^` is not mentioned anywhere, outside the context of brace sequences. – Charles Duffy Feb 20 '20 at 19:00
  • Great, I wrote so much regex these days, that I didn't even think that this is not part of the specs! I would accept this as an answer. Thanks! – HelloWorld Feb 20 '20 at 19:01

1 Answers1

1

This is not a place where Python fails to comply with the POSIX specification. UNIX pattern matching syntax does not require ^ to have any special meaning, except in a square-bracket character-set description.

See:


This makes sense: Globs are implicitly anchored -- they always match only at the beginning, so there's no reason to support an explicit anchor.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441