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?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With