Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SHA1 string regex for python [duplicate]

Tags:

python

regex

sha1

I need to check a string is a valid SHA1 string, like

 '418c1f073782a1c855890971ff18794f7a298f6d'

I didn't know the rules for that, for example whether a number and a letter is a must? or how many number or letters are minimum?

Could anybody advise any regex for matching in python?

like image 468
skydoor Avatar asked Aug 26 '15 18:08

skydoor


2 Answers

I believe it's faster to avoid using regex. A SHA1 is a random 40-digit hexidecimal number, so if you can't convert it to a hex and it's not 40 characters in length, it's not a SHA1:

def is_sha1(maybe_sha):
    if len(maybe_sha) != 40:
        return False
    try:
        sha_int = int(maybe_sha, 16)
    except ValueError:
        return False
    return True
like image 130
mVChr Avatar answered Nov 13 '22 19:11

mVChr


Use this regex:

\b[0-9a-f]{40}\b

Because it is a hexadecimal string with exactly 40 characters. You could also cast it as an integer as suggested below in another answer, however, this is the regex solution.

An example:

import re
pattern = re.compile(r'\b[0-9a-f]{40}\b')
match = re.match(pattern, '418c1f073782a1c855890971ff18794f7a298f6d')
print match.group(0)  # 418c1f073782a1c855890971ff18794f7a298f6d
like image 7
lollercoaster Avatar answered Nov 13 '22 18:11

lollercoaster