Git Commit SHA in GO
Match Git commit hashes, both short (7 chars) and full (40 chars) forms.
Try it in the GO tester →Pattern
regexGO
\b[0-9a-f]{7,40}\b (flags: g)Go (RE2) code
goGo
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`\b[0-9a-f]{7,40}\b`)
input := `commit 75d2cb0`
for _, match := range re.FindAllString(input, -1) {
fmt.Println(match)
}
}Uses `regexp.MustCompile` (panics on bad patterns at startup) and `FindAllString` for all matches.
How the pattern works
Hexadecimal string of 7 to 40 lowercase characters, word-bounded. Covers Git's abbreviated SHAs and full SHA-1 hashes.
Examples
Input
commit 75d2cb0Matches
75d2cb0
Input
e7827cc1234567890abcdef1234567890abcdef1Matches
e7827cc1234567890abcdef1234567890abcdef1
Input
zzzzzzzNo match
—