PatternRegex
Match a git commit hash
Match a git commit hash in its short or full form — 7 to 40 lowercase hex characters, the same range git itself accepts as an abbreviation.
Last updated
Matches
- fixed in a1b2c3d today
- revert 9f8e7d6c5b4a3f2e1d0c9b8a7f6e5d4c3b2a1f0e please
- ordinary word deadbeef also matches
Doesn’t match
- ABCDEF1 is uppercase only
- too-short a1b2c3 stays put
Why it’s written this way
Git's short hashes are usually 7 characters and its full SHA-1 hashes are 40, so [0-9a-f]{7,40} covers the whole legitimate range in one bounded repetition, with \b on each side to avoid matching a slice out of a longer run of hex-looking characters.
Restricting the character class to lowercase 0-9a-f is deliberate: git normalizes hashes to lowercase, so requiring lowercase here rules out a class of false positives from uppercase hex tokens that are clearly something else.
Edge cases to know
- →Any ordinary lowercase hex word in the right length range matches, hash or not — 'deadbeef' is a real English-adjacent word to a git user and also a perfectly valid 8-character hex string, so it matches here with no way to tell the difference from context alone.
- →It is deliberately case-sensitive to lowercase only — a hash pasted or displayed in uppercase (some tools do this) will not match unless it's lowercased first.
- →It cannot distinguish a short hash that is ambiguous in a given repository (matches more than one commit) from one that uniquely identifies a commit — that check requires the actual git object database, not a regex.