ISBN-13 in GO
Match 13-digit ISBNs starting with 978 or 979, with optional hyphens or spaces.
Try it in the GO tester →Pattern
regexGO
\b97[89][\- ]?(?:\d[\- ]?){9}\d\b (flags: g)Go (RE2) code
goGo
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`\b97[89][\- ]?(?:\d[\- ]?){9}\d\b`)
input := `978-0-306-40615-7`
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
The 978 or 979 GS1 prefix anchors the match, followed by nine digits (with optional separators) and a final check digit.
Examples
Input
978-0-306-40615-7Matches
978-0-306-40615-7
Input
9780306406157Matches
9780306406157