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
+11.3k Golang : Simple file scaning and remove virus example
+29.5k Golang : How to declare kilobyte, megabyte, gigabyte, terabyte and so on?
+15.8k Golang : Get sub string example
+21.7k Golang : Join arrays or slices example
+52k Golang : How to get struct field and value by name
+6.4k Golang : When to use make or new?
+11.3k Golang : Change date format to yyyy-mm-dd
+7.9k Golang : How To Use Panic and Recover
+4.8k Golang : Get a list of crosses(instruments) available to trade from Oanda account
+7.2k Golang : Check to see if *File is a file or directory
+10.2k Android Studio : Simple input textbox and intercept key example
+9.2k Facebook : Getting the friends list with PHP return JSON format