25% off

Use code FUNCMAIN at checkout for 25% off all premium courses.

Get started →
Regular Expression Matching in Go
Code Snippet

Regular Expression Matching in Go

go

Regular expressions in Go are handled by the regexp package, which provides powerful pattern matching capabilities. The MatchString function is the simplest way to check if a pattern exists in a string, returning a boolean. For more complex operations, MustCompile creates a compiled regular expression object that can be reused efficiently.

Once you have a compiled regex, you can use methods like FindString to find the first match, or FindAllString to find all matches. The -1 parameter in FindAllString means find all occurrences rather than limiting the results. This compiled approach is significantly faster when you need to match against multiple strings.

Here’s a comprehensive example showing different regex matching techniques:

package main

import (
  "fmt"
  "regexp"
)

func main() {
  // Simple boolean check
  text := "Contact: email@example.com or call 555-1234"
  emailPattern := regexp.MustCompile(`[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}`)

  if emailPattern.MatchString(text) {
    fmt.Println("Email found in text")
  }

  // Find first match
  email := emailPattern.FindString(text)
  fmt.Println("First email:", email) // Output: email@example.com

  // Find all matches
  phonePattern := regexp.MustCompile(`\d{3}-\d{4}`)
  phones := phonePattern.FindAllString(text, -1)
  fmt.Println("Phones found:", phones) // Output: [555-1234]

  // Using MatchString for simple patterns
  hasDigits, _ := regexp.MatchString(`\d`, text)
  fmt.Println("Contains numbers:", hasDigits) // Output: true
}

Regular expressions are powerful for validation, parsing, and searching tasks. However, for simple literal string searches, consider using strings.Contains for better performance. Understanding when to use regex versus simpler string functions will help you write more efficient Go applications.

Further Reading:

If you found this snippet useful, you may also enjoy some of the other content on the site: