How to match specific Unix shell-style strings using Python's fnmatch?

77 views Asked by At

I would like to create a Unix shell-style pattern that will only match strings with specific suffixes. The pattern in question starts with 0.1 and can finish with test or alpha or . .

This means that 0.1test and 0.1alpha should match but not 0.1beta or 0-1alpha. I've constructed the following patterns:

  1. 0.1{.,test,alpha}
  2. 0.1{["."],["test"],["alpha"]}

but both fail when tested as such:

import fnmatch
result = fnmatch.fnmatch(v, glob_pattern)
if result:
    print('SUCCESS')
else:
    print('FAILURE')
1

There are 1 answers

0
blhsing On

The fnmatch.fnmatch function does not support curly braces in the glob pattern.

Instead, you can install the braceexpand module to expand a pattern with curly braces into all possible strings that the pattern represents, so that each of them can then be passed to fnmatch.fnmatch for a match:

from fnmatch import fnmatch
from braceexpand import braceexpand

def brace_fnmatch(name, pattern):
    return any(fnmatch(name, p) for p in braceexpand(pattern))

so that:

for name in '0.1test', '0.1alpha', '0.1beta', '0-1alpha':
    print(name, end=' ')
    if brace_fnmatch(name, '0.1{.,test,alpha}'):
        print('matches')
    else:
        print('does not match')

outputs:

0.1test matches
0.1alpha matches
0.1beta does not match
0-1alpha does not match

Demo: https://replit.com/@blhsing1/ColorfulCornsilkGigabyte