Golang : Extract part of string with regular expression
Below is a simple example of how to extract a specific part of a string with the help of regular expression. For example, we are interested in extracting the part that starts with #$
from couple of strings such as
#$q4 revenue for 2017
revenue #$q2 for 2017
2017 revenue is #$q3
Here you go!
package main
import (
"fmt"
"regexp"
)
func main() {
str1 := "#$q4 revenue for 2017"
str2 := "revenue #$q2 for 2017"
str3 := "2017 revenue is #$q3"
// regular expression pattern
regE := regexp.MustCompile("\\#\\$q[1-4]")
fmt.Println(regE.FindAllString(str1, -1))
fmt.Println(regE.FindAllString(str2, -1))
fmt.Println(regE.FindAllString(str3, -1))
str4 := []string{str3, str1, str2}
for k, v := range str4 {
fmt.Println(k, regE.FindAllString(v, -1))
}
}
Output:
[#$q4]
[#$q2]
[#$q3]
0 [#$q3]
1 [#$q4]
2 [#$q2]
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
+13.7k Golang : convert rune to unicode hexadecimal value and back to rune character
+7.7k Golang : Check from web if Go application is running or not
+18k Golang : Get path name to current directory or folder
+10.1k Golang : Simple Jawi(Yawi) to Rumi(Latin/Romanize) converter
+7k Golang : Fixing Gorilla mux http.FileServer() 404 problem
+27.2k Golang : Convert integer to binary, octal, hexadecimal and back to integer
+9.4k Random number generation with crypto/rand in Go
+19.1k Golang : Fix cannot download, $GOPATH not set error
+17.5k Golang : Iterate linked list example
+20.2k Golang : Pipe output from one os.Exec(shell command) to another command
+10.3k Golang : ISO8601 Duration Parser example
+14.2k Golang : How to determine if user agent is a mobile device example