To split a string into an array using a regular expression delimiter in Golang, you can use the regexp
package along with the Split
function. Here is an example:
package main
import (
"fmt"
"regexp"
)
func main() {
str := "Hello, World! This is a sample string.123"
regex := regexp.MustCompile(`[^a-zA-Z]+`) // regular expression to split string using non-alphabetic characters as delimiter
result := regex.Split(str, -1)
fmt.Println(result)
}
In this example, we first define the input string str
and the regular expression regex
. The regular expression [^a-zA-Z]+
matches any sequence of non-alphabetic characters.
Then, we use the Split
function of the regexp
package to split the string using the regular expression as the delimiter. The second argument to Split
is the number of splits to perform. Passing -1
means to split as many times as possible.
Finally, we print the resulting array result
. In this example, the output will be:
[Hello World This is a sample string]
Note that the regular expression can be customized according to your specific delimiter requirements.