Golang matching: Difference between revisions
From wikinotes
(→Regexp) |
|||
(One intermediate revision by the same user not shown) | |||
Line 28: | Line 28: | ||
isTrue, err := regexp.Match("^[a-z]+$", "foobar") // match | isTrue, err := regexp.Match("^[a-z]+$", "foobar") // match | ||
</syntaxhighlight> | |||
Regexp Flags (multiline, case-insensitive, ...) | |||
<syntaxhighlight lang="go"> | |||
// go uses a match-prefix to indicate regexp flags | |||
// | |||
// (?...) where '...' is flags | |||
// flags: | |||
// m: multiline regex | |||
// i: case-insensitive | |||
// s: single-line mode '.' matches '\n' | |||
// | |||
// ex. | |||
regexp.MustCompile(`^\s+`) // matches leading whitespace on first line | |||
regexp.MustCompile(`(?m)^\s+`) // matches leading whitespace on every line | |||
</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) --> |
Latest revision as of 17:50, 17 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") // matchRegexp Flags (multiline, case-insensitive, ...)
// go uses a match-prefix to indicate regexp flags // // (?...) where '...' is flags // flags: // m: multiline regex // i: case-insensitive // s: single-line mode '.' matches '\n' // // ex. regexp.MustCompile(`^\s+`) // matches leading whitespace on first line regexp.MustCompile(`(?m)^\s+`) // matches leading whitespace on every lineSubstitute, 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]) }) }