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
+8k Golang : Multiplexer with net/http and map
+7k Javascript : How to get JSON data from another website with JQuery or Ajax ?
+7.6k Golang : Mapping Iban to Dunging alphabets
+17.5k Golang : delete and modify XML file content
+7.4k Golang : Rename part of filename
+5.9k Golang : Compound interest over time example
+43.3k Golang : Get hardware information such as disk, memory and CPU usage
+35.9k Golang : Get file last modified date and time
+21.1k Golang : Convert(cast) string to rune and back to string example
+35.2k Golang : Strip slashes from string example
+14.2k Golang : Convert IP version 6 address to integer or decimal number
+10.1k Golang : Text file editor (accept input from screen and save to file)