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
+5.6k Golang : Derive cryptographic key from passwords with Argon2
+7.1k Golang : Reverse text lines or flip line order example
+16k Golang : delete and modify XML file content
+6k Ubuntu : connect() to unix:/var/run/php5-fpm.sock failed (13: Permission denied) while connecting to upstream
+13.5k Golang : Find commonalities in two slices or arrays example
+16.1k Golang : Find smallest number in array
+12.1k Golang : Convert(cast) int to int64
+19.1k Golang : Pipe output from one os.Exec(shell command) to another command
+9.4k Golang : Select region of interest with mouse click and crop from image
+6.9k Golang : Regular Expression find string example
+6.9k Golang : Tell color name with OpenCV example
+11.2k Golang : Arithmetic operation with numerical slices or arrays example