Golang : Regular Expression find string example
This is a simple tutorial on how to use Golang's regexp package to find certain string value in a string. Nothing fancy. Just writing this down for future reference.
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/")
matchSlice := regE.Find(searchByte)
fmt.Printf("%s \n", matchSlice) // if found, return leftmost match, without 'abc'
matchSlice2 := regE.FindAll(searchByte, 500)
fmt.Printf("%s \n", matchSlice2) // if found, return all successive matches
oid := regE.NumSubexp()
fmt.Printf("OID is %d \n", oid)
// this is how to search by string
matchSlice3 := regE.FindAllString(string(searchByte), -1)
fmt.Printf("%s \n", matchSlice3) // if found, return all successive matches
}
See also : Golang : Regular Expression for alphanumeric and underscore
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+10.1k Use systeminfo to find out installed Windows Hotfix(s) or updates
+5.6k Golang : Calculate diameter, circumference, area, sphere surface and volume
+5.7k Get Facebook friends working in same company
+31.3k Golang : Smarter Error Handling with strings.Contains()
+21.2k Golang : Convert Unix timestamp to UTC timestamp
+4.5k Golang : fmt.Println prints out empty data from struct
+6.4k Golang : Rename part of filename
+26.1k Golang : Record voice(audio) from microphone to .WAV file
+6.8k Swift : Convert (cast) String to Double
+4.1k Swift : Convert (cast) Float to Int or Int32 value
+8.1k Golang : Timeout example
+25.1k Golang : Calculate future date with time.Add() function