Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
regular expression solution in Clear category for Unix Match. Part 1 by hbczmxy
"""
Unix Match. Part 1 (Moderate)
You need to find out if the given unix pattern matches the given filename.
Let me show you what I mean by matching the filenames in the unix-shell.
For example, * matches everything and *.txt matches all of the files that have txt extension.
Here is a small table that shows symbols that can be used in patterns.
* matches everything
? matches any single character
Input: Two arguments. Both are strings.
Output: Bool.
"""
def unix_match(filename: str, pattern: str) -> bool:
import re
# Replace "." in file extensions such as ".txt" with regex "\."
if '.' in pattern:
pattern = pattern.replace('.', '\.')
# Replace all '*' in pattern with regex '.*'
if '*' in pattern:
pattern = pattern.replace('*', r'.*')
# Replace all '?' in filename with regex '.{1}'
if '?' in pattern:
pattern = pattern.replace('?', r'.{1}')
# if regex match the entire filename, return True, False otherwise.
match = re.match(pattern, filename)
if match != None and match.group() == filename:
return True
else:
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('log12.txt', 'log?.txt') == False
assert unix_match('log12.txt', 'log??.txt') == True
assert unix_match("l.txt","???*") == True ,"&& contains '*' and '?' &&"
assert unix_match("txt","????*") == False, "**Filename should be 4 chars long**"
print("Coding complete? Click 'Check' to earn cool rewards!")
Sept. 14, 2021