Last active
November 20, 2017 03:23
-
-
Save craftgear/5d362c9bbc47f6b27426a9ced122175a to your computer and use it in GitHub Desktop.
split a string into a slice of strings by regexp (goで正規表現を使って文字列を分割する)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How to use:
=> ["Lorem", "ipsum", "dolor"]