Skip to content

Instantly share code, notes, and snippets.

@ochaloup
Last active July 31, 2019 18:00
Show Gist options
  • Select an option

  • Save ochaloup/69dd7569c8ed0157e4b72993a3deace4 to your computer and use it in GitHub Desktop.

Select an option

Save ochaloup/69dd7569c8ed0157e4b72993a3deace4 to your computer and use it in GitHub Desktop.
just testing to sort by number extracted from string with regexp
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