Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
convert into regex solution in Clear category for Unix Match. Part 3 by kurosawa4434
from re import match, escape
def unix_match(filename, pattern):
def convert_regex_inside_brackets(sub_pattern):
if sub_pattern == '[!]':
return escape(sub_pattern)
first_chr = '^' if sub_pattern[1] == '!' else sub_pattern[1]
func_esc = lambda c: escape(c) if c != '-' else c
return ('['
+ first_chr
+ ''.join(map(func_esc, sub_pattern[2:-1]))
+ ']')
def convert_regex_outside_brackets(sub_pattern):
wildcards = {'*': '.*', '?': '.'}
escaping = lambda c: wildcards[c] if c in wildcards else escape(c)
return ''.join(map(escaping, sub_pattern))
rest = pattern
regex = ''
while rest:
m1 = match('(\[.[^\]]*\])(.*)', rest) # inside of brackets ([....])...
m2 = match('([^\[]+)(\[.*)', rest) # outside of brackets (......)[..
if m1:
regex += convert_regex_inside_brackets(m1.group(1))
rest = m1.group(2)
elif m2:
regex += convert_regex_outside_brackets(m2.group(1))
rest = m2.group(2)
else:
regex += convert_regex_outside_brackets(rest)
break
return match(regex, filename) is not None
if __name__ == '__main__':
print("Example:")
print(unix_match('somefile.txt', '*'))
# These "asserts" are used for self-checking and not for an auto-testing
assert unix_match('somefile.txt', '*') == True
assert unix_match('other.exe', '*') == True
assert unix_match('my.exe', '*.txt') == False
assert unix_match('log1.txt', 'log?.txt') == True
assert unix_match('log1.txt', 'log[1234567890].txt') == True
assert unix_match('log12.txt', 'log?.txt') == False
assert unix_match('log12.txt', 'log??.txt') == True
print("Coding complete? Click 'Check' to earn cool rewards!")
Feb. 24, 2018
Comments: