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
+29.4k Golang : Get time.Duration in year, month, week or day
+5k JavaScript/JQuery : Redirect page examples
+37k Upload multiple files with Go
+4.4k MariaDB/MySQL : How to get version information
+17.1k Golang : Get future or past hours, minutes or seconds
+35.7k Golang : Converting a negative number to positive number
+8.9k Golang : does not implement flag.Value (missing Set method)
+19k Golang : Execute shell command
+9.8k Golang : Get login name from environment and prompt for password
+13.6k Golang : Human readable time elapsed format such as 5 days ago
+12.8k Golang : Skip blank/empty lines in CSV file and trim whitespaces example
+10k Golang : cannot assign type int to value (type uint8) in range error