Git Commit Hash Regex

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

Match Git commit hashes: 7-40 character hexadecimal strings.

Test This Pattern →

Pattern Breakdown

Understanding the regex pattern ^[0-9a-f]{7,40}$:

  • ^ - Start of string
  • $ - End of string
  • [...] - Character class
  • {n,m} - Quantifier (n to m times)

Examples

Input Result Explanation
a1b2c3d ✓ Match Short hash (7 chars)
a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0 ✗ No Match Contains invalid chars

Code Examples

JavaScript

JavaScript
const pattern = /^[0-9a-f]{7,40}$/;
const text = "a1b2c3d";

// Test if string matches
if (pattern.test(text)) {
  console.log("Valid!");
}

// Extract matches
const matches = text.match(pattern);
console.log(matches);

Python

Python
import re

pattern = r'^[0-9a-f]{7,40}$'
text = "a1b2c3d"

# Test if string matches
if re.match(pattern, text):
    print("Valid!")

# Find all matches
matches = re.findall(pattern, text)
print(matches)

PHP

PHP
<?php
$pattern = '/^[0-9a-f]{7,40}$/';
$text = "a1b2c3d";

// Test if string matches
if (preg_match($pattern, $text)) {
    echo "Valid!";
}

// Find all matches
preg_match_all($pattern, $text, $matches);
print_r($matches);
?>

Java

Java
import java.util.regex.*;

String pattern = "^[0-9a-f]{7,40}$";
String text = "a1b2c3d";

Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(text);

if (m.matches()) {
    System.out.println("Valid!");
}

Use Cases

Common applications: Git integrations, CI/CD pipelines, code review tools

Frequently Asked Questions

What is the regex pattern for git commit hash regex?
The regex pattern is: ^[0-9a-f]{7,40}$. Match Git commit hashes: 7-40 character hexadecimal strings.
How do I use the git commit hash regex pattern in JavaScript?
In JavaScript: const regex = new RegExp('^[0-9a-f]{7,40}$'); or const regex = /^[0-9a-f]{7,40}$/;
Does this pattern work in Python?
Yes, use: import re; pattern = re.compile(r'^[0-9a-f]{7,40}$') in Python. Most regex patterns are cross-language compatible.
What are common use cases for git commit hash regex?
Git integrations, CI/CD pipelines, code review tools

Related Regex Patterns

More Regex Tools

GetDevUtils offers a suite of developer tools including: