I'm trying to find a good way to split a string using a regular expression instead of a string. Thanks
http://nsf.github.io/go/strings.html?f:Split!
The Split() method in Golang (defined in the strings library) breaks a string down into a list of substrings using a specified separator. The method returns the substrings in the form of a slice.
In Go strings, you are allowed to split a string into a slice with the help of the following functions. These functions are defined under the strings package so, you have to import strings package in your program for accessing these functions: 1.
split(String regex) method splits this string around matches of the given regular expression. This method works in the same way as invoking the method i.e split(String regex, int limit) with the given expression and a limit argument of zero. Therefore, trailing empty strings are not included in the resulting array.
You can use regexp.Split
to split a string into a slice of strings with the regex pattern as the delimiter.
package main import ( "fmt" "regexp" ) func main() { re := regexp.MustCompile("[0-9]+") txt := "Have9834a908123great10891819081day!" split := re.Split(txt, -1) set := []string{} for i := range split { set = append(set, split[i]) } fmt.Println(set) // ["Have", "a", "great", "day!"] }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With