Regular Expressions in Go with Examples: A Complete Guide for Beginners

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Regular Expressions in Go (Golang): A Complete Guide for Beginners



Regular expressions (regex) are a powerful tool for searching, extracting, and replacing text based on specified patterns. In the Go language (Golang), working with regular expressions is implemented through the standard regexp package. In this article, we will cover the basics of working with regexp in Go, examine key functions, and provide practical examples to help you start using regular expressions in your projects.



What are regular expressions and why are they needed in Go?



A regular expression is a sequence of characters that defines a pattern for searching in text. For example, you can check if a string contains an email, phone number, or a specific data format. In Go, the regexp package provides functions for compiling patterns, searching for matches, replacing text, and extracting substrings.



Main capabilities of regexp:

  • Search — checking for the presence of a substring matching the pattern.
  • Extraction — obtaining all matches or individual groups.
  • Replace — replacing found fragments with other text.
  • Validation — checking the format of a string (email, password, URL).


Installing and importing the regexp package



The regexp package is part of the Go standard library, so nothing needs to be installed. To use it, simply import it at the beginning of your file:



import (    "fmt"    "regexp")


1. Compiling a regular expression: Compile and MustCompile



The first step in working with regular expressions is compiling the pattern. In Go, there are two main ways:



  • regexp.Compile(expr) — returns a compiled expression and an error if the pattern is invalid.
  • regexp.MustCompile(expr) — similar, but causes a panic on error. Convenient for static patterns.


Example:



package main

import ( "fmt" "regexp")

func main() { // Using MustCompile since the pattern is known to be valid re := regexp.MustCompile(`[a-z]+`) // Compile with error handling re2, err := regexp.Compile(`[0-9]+`) if err != nil { fmt.Println("Compilation error:", err) return } fmt.Println(re, re2)}


2. Basic search and check methods



After compilation, we have a *regexp.Regexp object with a set of methods. Let's look at the most useful ones.



MatchString — checking for a match

The MatchString(s string) bool method returns true if the string contains at least one match to the pattern.



re := regexp.MustCompile(`go`)fmt.Println(re.MatchString("golang"))   // truefmt.Println(re.MatchString("python"))   // false


FindString — finding the first match

Returns the first substring that matches the pattern.



re := regexp.MustCompile(`[0-9]+`)fmt.Println(re.FindString("Price: 100 rubles, discount 20%")) // "100"


FindAllString — finding all matches

Returns a slice of all found strings. The second argument is the maximum number of matches (-1 for all).



re := regexp.MustCompile(`[0-9]+`)result := re.FindAllString("Price: 100 rubles, discount 20%", -1)fmt.Println(result) // ["100", "20"]


3. Extracting groups using subexpressions



Parentheses in a pattern create capturing groups. The FindStringSubmatch method returns a slice where the first element is the full match, and subsequent elements are the group values.



re := regexp.MustCompile(`(\\d{4})-(\\d{2})-(\\d{2})`)date := "Date: 2023-12-25"matches := re.FindStringSu                

Blogs

Book Recommendations