Regular Expressions in Go: Complete Guide with Examples

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 with Examples: In Practice

\n\n

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

\n\n

Basics of the regexp Package

\n\n

The regexp package provides two main ways to compile a regular expression:

\n\n
    \n
  • regexp.Compile(pattern string) (*Regexp, error) — compiles the pattern and returns a Regexp object or an error if the pattern is invalid.
  • \n
  • regexp.MustCompile(pattern string) *Regexp — does the same but calls panic on error. Convenient for static patterns defined at initialization time.
  • \n
\n\n

It is recommended to use MustCompile for patterns that are guaranteed to be correct (e.g., hardcoded in the code) and Compile for dynamic patterns obtained from the user or an external source.

\n\n

Example 1: Finding a Substring (FindString)

\n\n

The FindString function returns the first match of the pattern as a string. If there are no matches, it returns an empty string.

\n\n
package main\n\nimport (\n    "fmt"\n    "regexp"\n)\n\nfunc main() {\n    text := "My email: example@mail.com, backup: test@example.org"\n    pattern := `[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}`\n\n    re := regexp.MustCompile(pattern)\n    match := re.FindString(text)\n\n    fmt.Println("Found email:", match) // Output: example@mail.com\n}
\n\n

Example 2: Finding All Matches (FindAllString)

\n\n

To find all matches, use FindAllString. The second argument is the maximum number of matches (-1 for all).

\n\n
package main\n\nimport (\n    "fmt"\n    "regexp"\n)\n\nfunc main() {\n    text := "Codes: ABC-123, XYZ-456, QWE-789"\n    pattern := `[A-Z]{3}-\\d{3}`\n\n    re := regexp.MustCompile(pattern)\n    matches := re.FindAllString(text, -1)\n\n    fmt.Println("Found codes:", matches)\n    // Output: [ABC-123 XYZ-456 QWE-789]\n}
\n\n

Example 3: Replacing Text (ReplaceAllString)

\n\n

ReplaceAllString replaces all matches of the pattern with the specified string. You can use capture groups with the syntax $1, $2, etc.

\n\n
package main\n\nimport (\n    "fmt"\n    "regexp"\n)\n\nfunc main() {\n    text := "Date: 2024-01-15, another date: 2023-12-31"\n    pattern := `(\\d{4})-(\\d{2})-(\\d{2})`\n\n    re := regexp.MustCompile(pattern)\n    // Change format from YYYY-MM-DD to DD.MM.YYYY\n    result := re.ReplaceAllString(text, "$3.$2.$1")\n\n    fmt.Println("Result:", result)\n    // Output: Date: 15.01.2024, another date: 31.12.2023\n}
\n\n

Example 4: Checking if a String Matches a Pattern (MatchString)

\n\n

The MatchString function returns true if the string contains at least one match of the pattern.

\n\n
package main\n\nimport (\n    "fmt"\n    "regexp"\n)\n\nfunc main() {\n    emails := []string{"user@example.com", "invalid-email", "admin@site.org"}\n    pattern := `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$`\n\n    re := regexp.MustCompile(pattern)\n    for _, email := range emails {\n        if re.MatchString(email) {\n            fmt.Printf("'%s' — valid email\\n", email)\n        } else {\n            fmt.Printf("'%s' — NOT a valid email\\n", email)\n        }\n    }\n    // Output:\n    // 'user@example.com' — valid email\n    // 'invalid-email' — NOT a valid email\n    // 'admin@site.org' — valid email\n}
\n\n

Example 5: Extracting Data Using Capture Groups (FindStringSubmatch)

\n\n

FindString

Blogs

Book Recommendations