Skip to content

Instantly share code, notes, and snippets.

@skyjia
Created July 15, 2020 06:39
Show Gist options
  • Save skyjia/a727df89b2473c5b83b18da696804e51 to your computer and use it in GitHub Desktop.
Save skyjia/a727df89b2473c5b83b18da696804e51 to your computer and use it in GitHub Desktop.

Revisions

  1. skyjia created this gist Jul 15, 2020.
    38 changes: 38 additions & 0 deletions regexp_group.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,38 @@
    package main

    import (
    "fmt"
    "regexp"
    )

    func main() {
    e := `^(?P<length>\d+)(?P<unit>[dmy])$`
    r := regexp.MustCompile(e)
    names := r.SubexpNames()
    tests := []string{
    `1234d`,
    `2y`,
    `234m`,
    `1234`,
    `mmmm`}
    for _, t := range tests {
    fmt.Printf("testing: %q\r\n", t)

    result := r.FindAllStringSubmatch(t, -1)
    matched := r.MatchString(t)
    fmt.Println("matched:", matched)

    if result != nil {
    m := map[string]string{}
    for i, n := range result[0] {
    m[names[i]] = n
    }

    fmt.Printf("<length>: %q\r\n", m["length"])
    fmt.Printf("<unit>: %q\r\n", m["unit"])
    }

    fmt.Println()
    }
    }