Skip to content
Go

Regular Expressions

Using the regexp package.

By EZ4Code Team
regexregex

Code

package main

import (
    "fmt"
    "regexp"
)

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

    // Find all
    matches := re.FindAllString("[email protected] [email protected]", -1)
    fmt.Println(matches)

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

    // Replace
    result := re.ReplaceAllString("[email protected]", "[REDACTED]")
    fmt.Println(result)

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

Explanation

The regexp package provides regex matching, searching, and replacement.

More Go Snippets