Skip to content
Go

Regular Expressions

Using the regexp package.

#regex#regex

Code

go
package main

import (
    "fmt"
    "regexp"
)

func main() {
    re := regexp.MustCompile(`\w+@(\w+)\.(\w+)`)

    // Find all
    matches := re.FindAllString("a@b.com c@d.com", -1)
    fmt.Println(matches)

    // Capture group
    sub := re.FindStringSubmatch("a@b.com")
    fmt.Println(sub) // [a@b.com b com]

    // Replace
    result := re.ReplaceAllString("a@b.com", "[REDACTED]")
    fmt.Println(result)

    // Validate
    matched, _ := regexp.MatchString(`^\d+$`, "12345")
    fmt.Println(matched)
}