simplify number extraction using regexp

This commit is contained in:
Gokcehan committed 2016-12-18 00:02:30 +03:00
1 parent 8d42bb166b
commit 8ae5f838c7
3 files changed
+39 -88

No files matched your search

+18 -40
View File
@@ -2,12 +2,11 @@ package main
import ( import (
"fmt" "fmt"
"log"
"path/filepath" "path/filepath"
"regexp"
"strconv" "strconv"
"strings" "strings"
"unicode" "unicode"
"unicode/utf8"
"github.com/mattn/go-runewidth" "github.com/mattn/go-runewidth"
) )
@@ -176,53 +175,32 @@ func humanize(size int64) string {
return "" return ""
} }
// This function extracts numbers from a string and returns with the rest. // This regexp is used to partition a given string as numbers and non-numbers.
// It is used for numeric sorting of files when the file name consists of // For instance, if your input is 'foo123bar456' you get a slice of 'foo',
// both digits and letters. // '123', 'bar', and '456'. This is useful for natural sorting which takes into
// // account values of numbers within strings.
// For instance if your input is 'foo123bar456' you get a slice of number var rePart = regexp.MustCompile(`\d+|\D+`)
// consisting of elements '123' and '456' and rest of the string as a slice
// consisting of elements 'foo' and 'bar'. The last return argument denotes
// whether or not the first partition is a number.
func extractNums(s string) (nums []int, rest []string, numFirst bool) {
var buf []rune
r, _ := utf8.DecodeRuneInString(s) func naturalLess(s1, s2 string) bool {
digit := unicode.IsDigit(r) parts1 := rePart.FindAllString(s1, -1)
numFirst = digit parts2 := rePart.FindAllString(s2, -1)
for _, c := range s { for i := 0; i < len(parts1) && i < len(parts2); i++ {
if unicode.IsDigit(c) == digit { if parts1[i] == parts2[i] {
buf = append(buf, c)
continue continue
} }
if digit { num1, err1 := strconv.Atoi(parts1[i])
i, err := strconv.Atoi(string(buf)) num2, err2 := strconv.Atoi(parts2[i])
if err != nil {
log.Printf("extracting numbers: %s", err) if err1 == nil && err2 == nil {
} return num1 < num2
nums = append(nums, i)
} else {
rest = append(rest, string(buf))
} }
buf = nil return parts1[i] < parts2[i]
buf = append(buf, c)
digit = !digit
} }
if digit { return len(parts1) < len(parts2)
i, err := strconv.Atoi(string(buf))
if err != nil {
log.Printf("extracting numbers: %s", err)
}
nums = append(nums, i)
} else {
rest = append(rest, string(buf))
}
return
} }
func min(a, b int) int { func min(a, b int) int {
+20 -23
View File
@@ -201,32 +201,29 @@ func TestHumanize(t *testing.T) {
} }
} }
func TestExtractNums(t *testing.T) { func TestNaturalLess(t *testing.T) {
names := []struct { tests := []struct {
s string s1 string
nums []int s2 string
rest []string expected bool
numFirst bool
}{ }{
{"foo123bar456", []int{123, 456}, []string{"foo", "bar"}, false}, {"foo", "bar", false},
{"123foo456bar", []int{123, 456}, []string{"foo", "bar"}, true}, {"bar", "baz", true},
{"a-1-1", []int{1, 1}, []string{"a-", "-"}, false}, {"foo", "123", false},
{"a-1-1.", []int{1, 1}, []string{"a-", "-", "."}, false}, {"foo1", "foobar", true},
{"a-1-1.txt", []int{1, 1}, []string{"a-", "-", ".txt"}, false}, {"foo1", "foo10", true},
{"a-1-10.txt", []int{1, 10}, []string{"a-", "-", ".txt"}, false}, {"foo2", "foo10", true},
{"a-10-1.txt", []int{10, 1}, []string{"a-", "-", ".txt"}, false}, {"foo1", "foo10bar", true},
{"foo2", "foo10bar", true},
{"foo1bar", "foo10bar", true},
{"foo2bar", "foo10bar", true},
{"foo1bar", "foo10", true},
{"foo2bar", "foo10", true},
} }
for _, name := range names { for _, test := range tests {
nums, rest, numFirst := extractNums(name.s) if b := naturalLess(test.s1, test.s2); b != test.expected {
if !reflect.DeepEqual(nums, name.nums) { t.Errorf("at input '%s' and '%s' expected '%t' but got '%t'", test.s1, test.s2, test.expected, b)
t.Errorf("at input '%s' expected '%v' but got '%v'", name.s, name.nums, nums)
}
if !reflect.DeepEqual(rest, name.rest) {
t.Errorf("at input '%s' expected '%v' but got '%v'", name.s, name.rest, rest)
}
if !numFirst == name.numFirst {
t.Errorf("at input '%s' expected '%t' but got '%t'", name.s, name.numFirst, numFirst)
} }
} }
} }
+1 -25
View File
@@ -48,31 +48,7 @@ func getFilesSorted(path string) []*File {
switch gOpts.sortby { switch gOpts.sortby {
case "natural": case "natural":
sortFilesStable(fi, func(i, j int) bool { sortFilesStable(fi, func(i, j int) bool {
nums1, rest1, numFirst1 := extractNums(fi[i].Name()) return naturalLess(strings.ToLower(fi[i].Name()), strings.ToLower(fi[j].Name()))
nums2, rest2, numFirst2 := extractNums(fi[j].Name())
if numFirst1 != numFirst2 {
return strings.ToLower(fi[i].Name()) < strings.ToLower(fi[j].Name())
}
if numFirst1 {
if nums1[0] != nums2[0] {
return nums1[0] < nums2[0]
}
nums1 = nums1[1:]
nums2 = nums2[1:]
}
for k := 0; k < len(nums1) && k < len(nums2); k++ {
if rest1[k] != rest2[k] {
return strings.ToLower(fi[i].Name()) < strings.ToLower(fi[j].Name())
}
if nums1[k] != nums2[k] {
return nums1[k] < nums2[k]
}
}
return strings.ToLower(fi[i].Name()) < strings.ToLower(fi[j].Name())
}) })
case "name": case "name":
sortFilesStable(fi, func(i, j int) bool { sortFilesStable(fi, func(i, j int) bool {