Skip to content

Instantly share code, notes, and snippets.

@craftgear
Last active November 20, 2017 03:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save craftgear/5d362c9bbc47f6b27426a9ced122175a to your computer and use it in GitHub Desktop.
Save craftgear/5d362c9bbc47f6b27426a9ced122175a to your computer and use it in GitHub Desktop.
split a string into a slice of strings by regexp (goで正規表現を使って文字列を分割する)
func splitByRegexp(str string, separator string) []string {
normalRe := "[^%s]*[%s]"
rawRe := `[^%s]*[%s]`
var re *regexp.Regexp
if strings.Index(separator, `\\`) > -1 {
re = regexp.MustCompile(fmt.Sprintf(normalRe, separator, separator))
} else {
re = regexp.MustCompile(fmt.Sprintf(rawRe, separator, separator))
}
strSlice := re.FindAllString(str, -1)
if strSlice == nil {
return []string{str}
}
// 元の文字列から最後の部分を取り出す
restStr := strings.Replace(str, strings.Join(strSlice, ""), "", -1)
if restStr != "" {
strSlice = append(strSlice, restStr)
}
return strSlice
}
@craftgear
Copy link
Author

How to use:

strSlice := splitByRegexp("Lorem, ipsum. dolor", "\.,")

=> ["Lorem", "ipsum", "dolor"]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment