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
+6k Golang : Generate multiplication table from an integer example
+8.3k How to show different content from website server when AdBlock is detected?
+4.8k Facebook : How to place save to Facebook button on your website
+22.4k Golang : Read directory content with filepath.Walk()
+24.8k Golang : How to print rune, unicode, utf-8 and non-ASCII CJK(Chinese/Japanese/Korean) characters?
+8.2k Golang : How To Use Panic and Recover
+8.9k Golang : On lambda, anonymous, inline functions and function literals
+16.1k Golang : How to reverse elements order in map ?
+22.2k Golang : Repeat a character by multiple of x factor
+19.7k Golang : Get current URL example
+11k Golang : Removes punctuation or defined delimiter from the user's input
+12.4k Golang : How to display image file or expose CSS, JS files from localhost?