Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Uncategorized category for Unix Match. Part 2 by Kurush
import re
def unix_match(filename: str, pattern: str) -> bool:
pattern = re.escape(pattern)
# Commented approach can't deal with brackets inside brackets interpretation ([c[]heckio).
#pattern = pattern.replace('\[', '[')
#pattern = pattern.replace('\]', ']')
while True:
left = pattern.find('\[')
if left == -1: break
right = pattern.find('\]', left)
if right == -1: break
# Sequence without any chars will never match
if left + 2 == right: return False
pattern = pattern[:left] + '[' + pattern[left+2:right] + ']' + pattern[right+2:]
# [!] is interpreted as ! symbol.
pattern = pattern.replace('[!]', '\[#\]')
pattern = pattern.replace('[!', '[^')
pattern = pattern.replace('\[#\]', '\[!\]')
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("checkio","[c[]heckio") == True
assert unix_match('somefile.txt', 'somefile.txt') == True
assert unix_match('1name.txt', '[!abc]name.txt') == True
assert unix_match('log1.txt', 'log[!0].txt') == True
assert unix_match('log1.txt', 'log[1234567890].txt') == True
assert unix_match('log1.txt', 'log[!1].txt') == False
print("Coding complete? Click 'Check' to earn cool rewards!")
May 5, 2021