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
+18.3k Golang : How to create new XML file ?
+17.8k Golang : Remove characters from string example
+7.3k Golang : Count JSON objects and convert to slice/array
+15.4k Golang : Get file last modified date and time
+2.3k Javascript : How to loop over and parse JSON data?
+15.3k PHP : Count number of JSON items/objects
+6.1k Golang : convert rune to unicode hexadecimal value and back to rune character
+10.4k Golang : GORM create record or insert new record into database example
+13.2k Golang : Convert file content into array of bytes
+6.7k Golang : Change date format to yyyy-mm-dd
+4.8k Golang : Resolve domain name to IP4 and IP6 addresses.
+2.1k Responsive Google Adsense