Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string using regular expression in Go

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!

like image 332
Julian Burgess Avatar asked Dec 16 '10 22:12

Julian Burgess


People also ask

How do you split a string in go?

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.

Can you slice a string in go?

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.

Can we split string using regex?

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.


1 Answers

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!"] } 
like image 134
openwonk Avatar answered Sep 28 '22 07:09

openwonk