DD
DevDash

Regex for Git Commit Hash

Regex Pattern

^[0-9a-f]{7,40}$

Git commit SHA hash (7-40 hex characters)

Quick Answer

The regex pattern for git commit hash is `^[0-9a-f]{7,40}$`. Git commit SHA hash (7-40 hex characters). This works in JavaScript, Python, Ruby, PHP, Java, and most regex engines that support PCRE syntax.

Test Examples

InputResult
a1b2c3d✓ Matches
abc1234567890def1234567890abcdef12345678✓ Matches
deadbeef✓ Matches
a1b2c3✗ No match
ABCDEF1✗ No match
not-a-hash✗ No match
g1234567✗ No match

Code Examples

javascript

const regex = /^[0-9a-f]{7,40}$/;
const isValid = regex.test(value);

python

import re
pattern = r'^[0-9a-f]{7,40}$'
if re.match(pattern, value):
    print("valid")

ruby

pattern = /^[0-9a-f]{7,40}$/
if value =~ pattern
  puts "valid"
end

php

if (preg_match('/^[0-9a-f]{7,40}$/', $value)) {
    echo "valid";
}

java

String pattern = "^[0-9a-f]{7,40}$";
boolean isValid = value.matches(pattern);

Frequently Asked Questions

Related Regex Patterns

Want API access + no ads? Pro coming soon.