Start free · Free tools · Fair usage limits
Browse Tools

Categories

Custom AI Solutions – AI2Flows
LIVE NEWS
Loading latest AI & SEO news…
Home›Tools›Regex Tester›Regex for Git commit hash
Regex pattern · validation

Regex for Git commit hash

Regex for git commit SHA: a tested pattern with examples, a plain-English breakdown, and code for JavaScript, Python, PHP, Java and Go.

Quick answer

Use /^[0-9a-f]{7,40}$/ as a Git commit hash regex. It matches "d959620" and "bb5c086a1f2e3d4c5b6a79881726354433221100", and rejects "12345" and "xyz1234". Repositories using SHA-256 object format have 64-character hashes; use {7,64} to allow them.

Last updated · Maintained by FreeAIToolz · How we test

/^[0-9a-f]{7,40}$/
  • d959620matches
  • bb5c086a1f2e3d4c5b6a79881726354433221100matches
  • 12345no match
  • xyz1234no match
  • D959620no match
  • bb5c086a1f2e3d4c5b6a798817263544332211000no match
Open in the full Regex Tester (replace, flags, groups) →

How this regex works

PartMeaning
^[0-9a-f]{7,40}$lowercase hex, from a 7-character short SHA up to a full 40-character SHA-1

Examples

InputResult
d959620✓ Matches
bb5c086a1f2e3d4c5b6a79881726354433221100✓ Matches
12345✗ No match
xyz1234✗ No match
D959620✗ No match
bb5c086a1f2e3d4c5b6a798817263544332211000✗ No match

Every example above is checked automatically in JavaScript and Python each time the site is built.

Limitations and edge cases

Repositories using SHA-256 object format have 64-character hashes; use {7,64} to allow them.

When to use this pattern

CI scripts, deploy tooling and changelog parsers.

Use it in your language

JavaScript

const re = /^[0-9a-f]{7,40}$/;
re.test(input); // true or false

Python

import re
pattern = re.compile(r'^[0-9a-f]{7,40}$')
bool(pattern.search(value))

PHP

$ok = preg_match('~^[0-9a-f]{7,40}$~', $value) === 1;

Java

Pattern pattern = Pattern.compile("^[0-9a-f]{7,40}$");
boolean ok = pattern.matcher(value).find();

Go

re := regexp.MustCompile(`^[0-9a-f]{7,40}$`)
ok := re.MatchString(value)

More regex patterns

Frequently asked questions

What is the regex for Git commit hash?
/^[0-9a-f]{7,40}$/. Repositories using SHA-256 object format have 64-character hashes; use {7,64} to allow them.
Which languages does this pattern work in?
It is tested in JavaScript and Python and uses syntax that also works in PHP (PCRE) and Java. It also works in Go’s RE2 engine.
Why does the pattern start with ^ and end with $?
They anchor the match to the whole string, so "abcd959620xyz" cannot pass just because it contains a valid part. To search for matches inside longer text, remove ^ and $ (use \b where word boundaries help) and add the g flag.