mvrpl
12/10/2018 - 9:41 PM

Checking if string match Glob patterns.

Checking if string match Glob patterns.

import re

def isGlob(_str):
    chars_oc = { '{': '}', '[': ']' }
    regex = r'\\(.)|(\?|^!|\*|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\)|\([^|]+\|[^\\)]+\))'

    if type(_str) != str or _str == "":
        return False
        
    if False in map(lambda key: True if _str.count(key) == _str.count(chars_oc[key]) else False, chars_oc.keys()):
        return False
        
    for match in re.finditer(regex, _str):
        if match[2]:
            return True

    return False

assert isGlob('/tmp/folderx/{[abc],[def]}')
assert not isGlob('/tmp/folderx/{[abc,[def]}')
assert isGlob('/tmp/folderx/*')
assert isGlob('*.js')
assert isGlob('??????.gif')
assert isGlob('/tmp/201810*[^9]')
assert isGlob('/tmp/arq_????.txt')
assert isGlob('/tmp/{ab,c{de, fh}}')
assert not isGlob('/tmp/{ab,c{de, fh}')
assert not isGlob("\\*.js")
assert not isGlob('abc.js')
assert not isGlob('abc/[abc.js')
assert not isGlob('abc/[^abc.js')
assert not isGlob('abc/[1-3.js')
assert isGlob('abc/{a,b}.js')
assert not isGlob('abc/{a,b.js')
assert isGlob('abc/{a-z}.js')

print("OK! TODOS TESTES PASSARAM.")