Golang matching

From wikinotes
Revision as of 05:25, 10 July 2022 by Will (talk | contribs) (→‎Regexp)

Documentation

path.Match (glob match) https://pkg.go.dev/path@go1.18.3#Match
regexp https://pkg.go.dev/regexp
go regex syntax https://pkg.go.dev/regexp/syntax

Match (glob)

import "path"

isTrue := path.Match("f*", "foo")  // glob match

Regexp

import "regexp"

isTrue, err := regexp.Match("^[a-z]+$", "foobar")  // match

Substitute, using regex capture groups

headerRx = regexp.MustCompile(fmt.Sprint(
    `(?P<head><[/]?[ \t]*h)`, // '<h'  '</h'
    `(?P<lv>[1-6])`,          // '1'
    `(?P<tail>[^>]*>)`,       // '>'
))

func incrementHeaders(html string) string {
    headerRx.ReplaceAllStringFunc(html, func(match string) string {
        submatches := headerRx.FindStringSubmatch(match)
        lv, _ := strconv.Atoi(submatches[2])
        return fmt.Sprint(submatches[1], lv+1, submatches[3])
    })
}