Golang regexp.FindAllIndex() and FindIndex() functions example

package regexp

Golang regexp.FindAllIndex() and FindIndex() functions usage example.

 package main

 import (
  "fmt"
  "regexp"
 )

 func main() {

  // regular expression pattern
  regE := regexp.MustCompile("/oid/([\\d]+)/")

  // simulate a search

  // first convert string to byte for Find() function
  searchByte := []byte("/oid/1/something_else/oid/2/")

  matchSlice := regE.FindIndex(searchByte)

  for _, v := range matchSlice {
 // found /oid/1/
 // and return location of the leftmost match
 fmt.Printf("position :[%v]\n", v)
  }

  // ---- find all index

  matchAllSlice := regE.FindAllIndex(searchByte, 500)

  for _, v := range matchAllSlice {
 // found /oid/1/ and /oid/2
 // and return locations of the all matches
 fmt.Printf("position :[%v]\n", v)
  }

 }

Output :

position :[0]

position :[7]

position :[[0 7]]

position :[[21 28]]

References :

http://golang.org/pkg/regexp/#Regexp.FindIndex

http://golang.org/pkg/regexp/#Regexp.FindAllIndex

Advertisement