Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Uncategorized category for Unix Match. Part 3 by Kurush
import re
def unix_match(filename: str, pattern: str) -> bool:
processed = ''
to_process = pattern
while True:
left = to_process.find('[')
if left == -1: break
right = to_process.find(']', left)
if right == -1: break
left2 = to_process.find('[', right + 1)
right2 = to_process.find(']', right + 1)
if (left2 == -1 and right2 != -1) or (left2 > right2):
right = right2
if (left2 == left + 2) and (right2 == right + 2):
right = right2
# Sequence without any chars will never match
if left + 1 == right: return False
processed = processed + re.escape(to_process[:left]) + '[' + to_process[left+1:right] + ']'
to_process = to_process[right+1:]
pattern = processed + re.escape(to_process)
# [!] is interpreted as ! symbol.
pattern = pattern.replace('[!]', '\[#\]')
pattern = pattern.replace('[!', '[^')
pattern = pattern.replace('\[#\]', '\[!\]')
pattern = pattern.replace('\*', '(.*)')
pattern = pattern.replace('\?', '(.{1})')
re_pattern = re.compile(pattern)
res = re_pattern.search(filename)
if res == None: return False
return filename == res.group(0)
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("[?*]","[[][?][*][]]") == True
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!")
May 5, 2021