Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Short and simple solution in Speedy category for Unix Match. Part 3 by r_tchaik
#simpler but forbidden here way:
# from fnmatch import fnmatch as unix_match
import re
def unix_match(filename: str, pattern: str) -> bool:
try:
pattern = pattern.replace(r'.', r'\.').replace(r'*', r'.*') \
.replace(r'!', r'^').replace(r'[^]', r'\[!\]')
if pattern.find(r'[?]') == -1:
pattern = pattern.replace(r'?', r'.')
return bool(re.match(pattern, filename))
except re.error:
return False
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!")
June 15, 2020
Comments: