Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
I've refused to reinvent the wheel solution in Creative category for Unix Match. Part 3 by suic
# This is a Pythonic solution
# from fnmatch import fnmatch as unix_match
# I've refused to reinvent the wheel :)
import re
unix_match = lambda n, p, m=re.match: m(translate(p), n) is not None
# Source: https://github.com/python/cpython/blob/3.6/Lib/fnmatch.py
def translate(pat):
"""Translate a shell PATTERN to a regular expression.
There is no way to quote meta-characters.
"""
i, n = 0, len(pat)
res = ''
while i < n:
c = pat[i]
i = i+1
if c == '*':
res = res + '.*'
elif c == '?':
res = res + '.'
elif c == '[':
j = i
if j < n and pat[j] == '!':
j = j+1
if j < n and pat[j] == ']':
j = j+1
while j < n and pat[j] != ']':
j = j+1
if j >= n:
res = res + '\\['
else:
stuff = pat[i:j].replace('\\','\\\\')
i = j+1
if stuff[0] == '!':
stuff = '^' + stuff[1:]
elif stuff[0] == '^':
stuff = '\\' + stuff
res = '%s[%s]' % (res, stuff)
else:
res = res + re.escape(c)
return r'(?s:%s)\Z' % res
Feb. 27, 2018
Comments: