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)

MatchString

(*regexp.Regexp) MatchString(string)

MatchReader

(*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

FindString

(*Regexp) FindString(string) string

""

FindIndex

(*Regexp) FindIndex([]byte) []int

nil

FindStringIndex

(*Regexp) FindStringIndex(string) []int

nil

FindReaderIndex

(*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

FindAll

(*Regexp) FindAll([]byte) [][]byte

nil

FindAllString

(*Regexp) FindAllString(string) []string

nil

FindAllIndex

(*Regexp) FindAllIndex([]byte) [][]int

nil

FindAllStringIndex

(*Regexp) FindAllStringIndex([]byte) [][]int

nil

These functions return the array of subcontents that represents

  1. the left-most match to a compiled regular expression
  2. 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


CategoryRicottone