Last active
July 31, 2019 18:00
-
-
Save ochaloup/69dd7569c8ed0157e4b72993a3deace4 to your computer and use it in GitHub Desktop.
just testing to sort by number extracted from string with regexp
This file contains hidden or 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
| package main | |
| import ( | |
| "fmt" | |
| "sort" | |
| "regexp" | |
| "strconv" | |
| ) | |
| type M struct { | |
| Name string | |
| } | |
| func main() { | |
| data := []M {M{"quickstart-1"}, M{"quickstart-10"}, M{"quickstart-0"}, M{"quickstart-2"}, M{"quickstart-3"}} | |
| pattern := regexp.MustCompile(`([0-9]+)$`) // number at the end | |
| sort.SliceStable(data, func(i, j int) bool { | |
| number1, _ := strconv.Atoi(pattern.FindStringSubmatch(data[i].Name)[1]) | |
| number2, _ := strconv.Atoi(pattern.FindStringSubmatch(data[j].Name)[1]) | |
| return number1 < number2 | |
| // return i < j | |
| }) | |
| fmt.Println(data) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment