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
+21.8k Golang : Encrypt and decrypt data with TripleDES
+9.5k Golang : Launch Mac OS X Preview (or other OS) application from your program example
+15.6k Golang : Get all local users and print out their home directory, description and group id
+4.8k Chrome : How to block socketloop.com links in Google SERP?
+12.6k Golang : HTTP response JSON encoded data
+6.1k Unix/Linux : How to open tar.gz file ?
+31.7k Golang : Example for ECDSA(Elliptic Curve Digital Signature Algorithm) package functions
+30.1k Golang : Record voice(audio) from microphone to .WAV file
+10.4k Golang : Random Rune generator
+6.7k Elasticsearch : Shutdown a local node
+11.9k How to tell if a binary(executable) file or web application is built with Golang?
+9.6k Golang : Scramble and unscramble text message by randomly replacing words