Golang matching: Difference between revisions
From wikinotes
(→Regexp) |
|||
Line 28: | Line 28: | ||
isTrue, err := regexp.Match("^[a-z]+$", "foobar") // match | isTrue, err := regexp.Match("^[a-z]+$", "foobar") // match | ||
</syntaxhighlight> | |||
Substitute, using regex capture groups | |||
<syntaxhighlight lang="go"> | |||
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]) | |||
}) | |||
} | |||
</syntaxhighlight> | </syntaxhighlight> | ||
</blockquote><!-- (regex) --> | </blockquote><!-- (regex) --> |
Revision as of 05:25, 10 July 2022
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") // matchSubstitute, 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]) }) }