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
+25.5k Golang : Copy directory - including sub-directories and files
+11.1k Golang : Generate QR codes for Google Authenticator App and fix "Cannot interpret QR code" error
+10k Golang : Chunk split or divide a string into smaller chunk example
+11.6k Golang : Get the IPv4 and IPv6 addresses for a specific network interface
+15k Golang : Example for RSA package functions
+9k Golang : Set image canvas or background to transparent
+4.7k Golang : Set horizontal, vertical scroll bars policies and disable interaction on Qt image
+19.5k Golang : How to validate URL the right way
+12.7k Golang : Convert slice to array
+7.5k PHP : Convert(cast) bigInt to string
+22.8k Golang : missing Mercurial command
+5.6k Golang : Find network service name from given port and protocol