MongoDB ObjectId in GO
Match MongoDB ObjectId values — 24-character hexadecimal strings.
Try it in the GO tester →Pattern
regexGO
\b[0-9a-fA-F]{24}\b (flags: g)Go (RE2) code
goGo
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`\b[0-9a-fA-F]{24}\b`)
input := `507f1f77bcf86cd799439011`
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
Word-bounded exactly 24 hex digits. Case-insensitive character class covers both upper and lower case forms produced by different drivers.
Examples
Input
507f1f77bcf86cd799439011Matches
507f1f77bcf86cd799439011
Input
id: 5f8d0d55b54764421b7156c4Matches
5f8d0d55b54764421b7156c4
Input
not an objectidNo match
—