codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🐹

Go (Golang)

37 / 72 topics
27Standard Library Overview28IO Package29Net Package30HTTP Package31JSON Package32XML Package33Time Package34OS Package35Fmt Package36Math Package37Regexp Package38Log Package39Flag Package40Context Package41Embed Package
Tutorials/Go (Golang)/Regexp Package
🐹Go (Golang)

Regexp Package

Updated 2026-04-20
3 min read

Regexp Package

The regexp package in Go (Golang) provides support for regular expressions, which are a powerful tool for pattern matching and text processing. Regular expressions allow you to search, match, replace, and split strings based on patterns. This guide will cover the basics of using the regexp package, including how to compile regular expressions, perform matches, and manipulate strings.

Introduction to Regular Expressions

Regular expressions (regex or regexp) are sequences of characters that define a search pattern. They can be used to match text based on specific rules. For example, you might use a regex to find all email addresses in a block of text or to validate user input against a certain format.

In Go, the regexp package provides a comprehensive set of functions and methods for working with regular expressions. It is part of the standard library, so you don't need to install any additional packages to use it.

Importing the Regexp Package

To start using the regexp package, you first need to import it into your Go program:

import (
    "fmt"
    "regexp"
)

Compiling Regular Expressions

Before you can use a regular expression, you must compile it. The Compile function in the regexp package compiles a string representation of a regular expression into a Regexp object.

Example: Basic Compilation

package main

import (
    "fmt"
    "regexp"
)

func main() {
    // Compile a simple regex to match email addresses
    re, err := regexp.Compile(`[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}`)
    if err != nil {
        fmt.Println("Error compiling regex:", err)
        return
    }

    // Test the regex with a sample email address
    match := re.MatchString("example@example.com")
    fmt.Println("Match found:", match) // Output: Match found: true
}

Explanation

  • regexp.Compile takes a string argument, which is the regular expression pattern.
  • It returns two values: a pointer to a Regexp object and an error. If the regex pattern is invalid, the error will be non-nil.
  • The MatchString method of the Regexp object checks if the given string matches the compiled regex.

Matching Strings

Once you have a compiled regular expression, you can use various methods to match strings against it.

Example: Finding All Matches

package main

import (
    "fmt"
    "regexp"
)

func main() {
    // Compile a regex to find all words in a string
    re := regexp.MustCompile(`\b\w+\b`)

    // Find all matches in the input string
    matches := re.FindAllString("Hello, world! This is a test.", -1)
    fmt.Println("Matches:", matches) // Output: Matches: [Hello world This is a test]
}

Explanation

  • regexp.MustCompile is similar to Compile, but it panics if the regex pattern is invalid. It's useful for static patterns that you know are correct.
  • The FindAllString method returns all non-overlapping matches of the regex in the input string as a slice of strings.

Replacing Strings

The regexp package also provides methods to replace parts of a string that match a regular expression.

Example: String Replacement

package main

import (
    "fmt"
    "regexp"
)

func main() {
    // Compile a regex to find all email addresses
    re := regexp.MustCompile(`[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}`)

    // Replace all email addresses with "[REDACTED]"
    result := re.ReplaceAllString("Contact us at example@example.com", "[REDACTED]")
    fmt.Println("Result:", result) // Output: Result: Contact us at [REDACTED]
}

Explanation

  • The ReplaceAllString method replaces all matches of the regex in the input string with a specified replacement string.

Splitting Strings

Regular expressions can also be used to split strings based on patterns.

Example: String Splitting

package main

import (
    "fmt"
    "regexp"
)

func main() {
    // Compile a regex to split on whitespace
    re := regexp.MustCompile(`\s+`)

    // Split the input string into words
    parts := re.Split("Hello, world! This is a test.", -1)
    fmt.Println("Parts:", parts) // Output: Parts: [Hello, world! This is a test.]
}

Explanation

  • The Split method splits the input string at each match of the regex and returns a slice of substrings.

Advanced Features

The regexp package offers many advanced features that can be used for more complex text processing tasks.

Example: Named Capturing Groups

package main

import (
    "fmt"
    "regexp"
)

func main() {
    // Compile a regex with named capturing groups
    re := regexp.MustCompile(`(?P<name>\w+) (?P<age>\d+)`)

    // Find the first match and extract named groups
    match := re.FindStringSubmatch("John 30")
    if len(match) > 0 {
        name := match[re.SubexpIndex("name")]
        age := match[re.SubexpIndex("age")]
        fmt.Printf("Name: %s, Age: %s\n", name, age) // Output: Name: John, Age: 30
    }
}

Explanation

  • Named capturing groups allow you to extract specific parts of a match by name.
  • SubexpIndex returns the index of the named group in the match slice.

Best Practices

  1. Compile Regular Expressions Once: If you have a static regex pattern that doesn't change, use regexp.MustCompile to compile it once and reuse the Regexp object.
  2. Error Handling: Always check for errors when compiling regular expressions, especially if patterns are dynamic or user-provided.
  3. Performance Considerations: Regular expressions can be computationally expensive. Use them judiciously and test their performance in your specific use case.

Conclusion

The regexp package in Go provides a powerful set of tools for working with regular expressions. Whether you need to search, match, replace, or split strings, the regexp package has you covered. By understanding how to compile patterns, perform matches, and manipulate strings, you can harness the full power of regular expressions in your Go applications.

Remember to always test your regex patterns thoroughly to ensure they behave as expected in different scenarios.


PreviousMath PackageNext Log Package

Recommended Gear

Math PackageLog Package