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 :
Advertisement
Something interesting
Tutorials
+16k Golang : Generate universally unique identifier(UUID) example
+20.5k Golang : Pipe output from one os.Exec(shell command) to another command
+4.3k Golang : Converting individual Jawi alphabet to Rumi(Romanized) alphabet example
+5.3k Javascript : Shuffle or randomize array example
+11.1k Golang : Web routing/multiplex example
+25.4k Golang : Generate MD5 checksum of a file
+15.6k Golang : Force download file example
+26.3k Golang : Calculate future date with time.Add() function
+15.3k Golang : Delete certain files in a directory
+12.7k Golang : Pass database connection to function called from another package and HTTP Handler
+3.7k Golang : Switch Redis database redis.NewClient
+10.5k Generate Random number with math/rand in Go