Compile regex and match patterns
Compile regex and match patterns
An expression in regexp describes a set of possible matches. Compile parses the pattern and returns a reusable *Regexp or an error. MatchString reports whether any part of the string matches. For an entire identifier, explicitly anchor both ends. A raw Go string (backticks) avoids a second layer of backslash escaping.
package main
import ( "fmt" "regexp")
func check(e error) { if e != nil { panic(e) }}
func main() { r, e := regexp.Compile(`^[A-Z]{2}-[0-9]{3}$`) check(e) for _, s := range []string{"AB-123", "xAB-123", "AB-12"} { fmt.Println(s, r.MatchString(s)) }}Here ^ and $ anchor the string in the default mode, [A-Z] is an ASCII letter range, and {2} requires two occurrences. The hyphen is literal outside a character class. Compile once before the loop instead of parsing the same pattern for every record. This checks syntax, not whether an ID exists in a database.
Expected output:
AB-123 truexAB-123 falseAB-12 falseHandle a bad pattern
package main
import ( "fmt" "regexp")
func main() { _, e := regexp.Compile(`[`) fmt.Println(e != nil) r := regexp.MustCompile(`tea`) fmt.Println(r.MatchString("iced tea"))}MustCompile panics on an invalid pattern; reserve it for fixed patterns you control. Use Compile with error handling for configurable patterns. MatchString is a search, so the second example also matches within a longer string. Limit input and pattern sizes when accepting external data.
Expected output:
truetrueTry it locally
Compile a pattern for exactly four ASCII digits. Print the match results for 2026, 26 and x2026.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Text processing 01: Compile regex and match patterns
Check the lesson objective before moving on.
Which call reports an invalid configurable pattern as an error?
Why add both anchors to an ID pattern?