Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
roll my own solution in Speedy category for Unix Match. Part 2 by ibonyun
def iter_pattern(pattern):
ipat = iter(pattern)
for x in ipat:
if x == '[':
want = True
options = []
x = next(ipat)
if x == '!':
want = False
x = next(ipat)
while x != ']':
options.append(x)
x = next(ipat)
if not options and not want:
for y in '[!]':
yield y, True
else:
yield ''.join(options), want
else:
yield x, True
def unix_match(filename: str, pattern: str) -> bool:
ipattern = iter_pattern(pattern)
for x in filename:
pat, want = next(ipattern)
if (x in pat) is not want:
return False
return True
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', 'somefile.txt') == True, "('somefile.txt', 'somefile.txt') == True"
assert unix_match('1name.txt', '[!abc]name.txt') == True, "('1name.txt', '[!abc]name.txt') == True"
assert unix_match('1name.txt', '[!abc]name.txt') == True, "('1name.txt', '[!abc]name.txt') == True"
assert unix_match('log1.txt', 'log[1234567890].txt') == True, "('log1.txt', 'log[1234567890].txt') == True"
assert unix_match('log1.txt', 'log[!1].txt') == False, "('log1.txt', 'log[!1].txt') == False"
assert unix_match("[!]check.txt","[!]check.txt") == True, '("[!]check.txt","[!]check.txt") == True'
print("Coding complete? Click 'Check' to earn cool rewards!")
May 5, 2020
Comments: