Regular Expressions
Start with Regular Expressions
The regexp package matches text patterns using Go’s RE2-based regular-expression engine.
What you’ll learn
- Explain the main purpose of regular expressions.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
regexp.MustCompile constructs a reusable pattern and panics if the pattern is invalid; use regexp.Compile when handling a pattern supplied by a user or another fallible source. MatchString checks for a match, and FindAllString extracts matching parts.
Go regexp supports a deliberately bounded feature set and does not offer every construct found in Perl-compatible engines, such as backreferences. Prefer simpler string operations when a regex adds no value.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import (
"fmt"
"regexp"
)
func main() {
pattern := regexp.MustCompile(`[0-9]+`)
text := "Boxes: 12, 7 and 35"
fmt.Println("Numbers:", pattern.FindAllString(text, -1))
fmt.Println("Contains number:", pattern.MatchString(text))
}
Output
Numbers: [12 7 35]
Contains number: trueTrace what the program does
The pattern matches one or more ASCII digits. FindAllString extracts the three number substrings in text order, while MatchString reports true.
Avoid common mistakes
- Backreferences such as \1 are not supported by Go regexp.
- A regex that matches anywhere is different from one anchored with ^ and $.
Try it yourself
Write a pattern that matches a word starting with capital G, then test it with MatchString.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Regular Expressions in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.