ISBN-10 in GO
Match 10-digit ISBNs, allowing optional hyphens or spaces between groups.
Try it in the GO tester →Pattern
regexGO
\b(?:\d[\- ]?){9}[\dXx]\b (flags: g)Go (RE2) code
goGo
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`\b(?:\d[\- ]?){9}[\dXx]\b`)
input := `0-306-40615-2`
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
Nine digits each followed by an optional hyphen or space, then a final check character which can be a digit or X (upper or lower case).
Examples
Input
0-306-40615-2Matches
0-306-40615-2
Input
0306406152Matches
0306406152
Input
080442957XMatches
080442957X