Go regexp
The regexp package provides regular expression functions.
Example
package main
import (
"fmt"
"regexp"
)
var (
Pattern1 = regexp.MustCompile(`^Chapter ([0-9]+)$`)
Pattern2 = regexp.MustCompile(`^Section ([A-F])$`)
)
func main() {
for _, h := range headers {
if Pattern1.MatchString(h) {
fmt.Println("chapter!")
continue
}
if Pattern2.MatchString(h) {
fmt.Println("section!")
continue
}
fmt.Println("unknown!")
}
}
Functions
These functions test if some content matches a compiled regular expression.
Name |
Signature |
Match |
(*regexp.Regexp) Match([]byte) |
(*regexp.Regexp) MatchString(string) |
|
(*regexp.Regexp) MatchReader(io.RuneReader) |
These functions return the subcontent that represent the left-most match to a compiled regular expression. If the function name includes Index, then the returned values are start and end indices. As an example:
loc := pattern.FindIndex(content) match := content[loc[0]:loc[1]]
Name |
Signature |
Returned if no match |
Find |
(*Regexp) Find([]byte) []byte |
nil |
(*Regexp) FindString(string) string |
"" |
|
(*Regexp) FindIndex([]byte) []int |
nil |
|
(*Regexp) FindStringIndex(string) []int |
nil |
|
(*Regexp) FindReaderIndex(io.RuneReader) []int |
nil |
These functions return the array of subcontents that represents all matches to a compiled regular expression.
Name |
Signature |
Returned if no match |
(*Regexp) FindAll([]byte) [][]byte |
nil |
|
(*Regexp) FindAllString(string) []string |
nil |
|
(*Regexp) FindAllIndex([]byte) [][]int |
nil |
|
(*Regexp) FindAllStringIndex([]byte) [][]int |
nil |
These functions return the array of subcontents that represents
- the left-most match to a compiled regular expression
- all matches to capture groups in the expression
As an example:
match := Pattern1.FindStringSubmatch("Chapter 12")
number := 0
if match != nil & len(match)>1 {
number = match[1]
}If the function name includes All, then the array includes all matches and all subgroup matches.
FindSubmatch FindStringSubmatch FindSubmatchIndex FindStringSubmatchIndex FindReaderSubmatchIndex FindAllSubmatch FindAllStringSubmatch FindAllSubmatchIndex FindAllStringSubmatchIndex
