unix_match_part_2.unix_match()   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nop 2
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
from re import search
2
3
4
def translate_pattern(pattern: str) -> str:
5
    return pattern.replace('.', '\.').replace('*', '.*').replace('?', '.').replace('[!', '[^').replace('[^]', '\[!\]')
6
7
8
def unix_match(filename: str, pattern: str) -> bool:
9
    translated_pattern = translate_pattern(pattern)
10
    return ('[]' not in translated_pattern) and bool(search(translated_pattern, filename))
11
12
13 View Code Duplication
if __name__ == "__main__":
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
14
    print("Example:")
15
    print(unix_match("somefile.txt", "*"))
16
17
    # These "asserts" are used for self-checking and not for an auto-testing
18
    assert unix_match("somefile.txt", "somefile.txt") == True
19
    assert unix_match("1name.txt", "[!abc]name.txt") == True
20
    assert unix_match("log1.txt", "log[!0].txt") == True
21
    assert unix_match("log1.txt", "log[1234567890].txt") == True
22
    assert unix_match("log1.txt", "log[!1].txt") == False
23
    print("Coding complete? Click 'Check' to earn cool rewards!")
24