Skip to content
Go

正则表达式

使用 regexp 包。

#regex#regex

Code

go
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)
}