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.5k Golang : Execute function at intervals or after some delay
+20.4k Golang : Convert seconds to minutes and remainder seconds
+12.7k Golang : How to pass map to html template and access the map's elements
+16.5k Golang : Aligning strings to right, left and center with fill example
+4.5k Golang : Display advertisement images or strings on random order
+8.9k Golang : Find and replace data in all files recursively
+3.7k Linux : sudo yum updates not working
+20.2k SSL : How to check if current certificate is sha1 or sha2
+3.5k Golang : Valued expressions and functions example
+9.4k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
+16.1k Golang : Find smallest number in array