1
1
mirror of https://github.com/walles/moar.git synced 2024-09-11 12:15:43 +03:00

Case insensitive search on lowercase-only pattern

This commit is contained in:
Johan Walles 2019-07-06 22:16:08 +02:00
parent ea5b4fdefe
commit 2f5c2da2e3
3 changed files with 39 additions and 10 deletions

View File

@ -6,6 +6,7 @@ import (
"math"
"os"
"regexp"
"unicode"
"github.com/gdamore/tcell"
)
@ -279,17 +280,29 @@ func ToPattern(compileMe string) *regexp.Regexp {
return nil
}
pattern, err := regexp.Compile(compileMe)
hasUppercase := false
for _, char := range compileMe {
if unicode.IsUpper(char) {
hasUppercase = true
}
}
// Smart case; be case insensitive unless there are upper case chars
// in the search string
prefix := "(?i)"
if hasUppercase {
prefix = ""
}
pattern, err := regexp.Compile(prefix + compileMe)
if err == nil {
// Search string is a regexp
// FIXME: Make this case insensitive if input is all-lowercase
return pattern
}
pattern, err = regexp.Compile(regexp.QuoteMeta(compileMe))
pattern, err = regexp.Compile(prefix + regexp.QuoteMeta(compileMe))
if err == nil {
// Pattern matching the string exactly
// FIXME: Make this case insensitive if input is all-lowercase
return pattern
}

View File

@ -218,4 +218,20 @@ func TestManPageFormatting(t *testing.T) {
func TestToPattern(t *testing.T) {
assert.Assert(t, ToPattern("") == nil)
// Test regexp matching
assert.Assert(t, ToPattern("G.*S").MatchString("GRIIIS"))
assert.Assert(t, !ToPattern("G.*S").MatchString("gRIIIS"))
// Test case insensitive regexp matching
assert.Assert(t, ToPattern("g.*s").MatchString("GRIIIS"))
assert.Assert(t, ToPattern("g.*s").MatchString("gRIIIS"))
// Test non-regexp matching
assert.Assert(t, ToPattern(")G").MatchString(")G"))
assert.Assert(t, !ToPattern(")G").MatchString(")g"))
// Test case insensitive non-regexp matching
assert.Assert(t, ToPattern(")g").MatchString(")G"))
assert.Assert(t, ToPattern(")g").MatchString(")g"))
}

12
test.sh
View File

@ -2,14 +2,10 @@
set -e -o pipefail
# Ensure we can cross compile
GOOS=linux GOARCH=386 go build
GOOS=darwin GOARCH=amd64 go build
# Unit tests first...
# Unit tests first
go test github.com/walles/moar/m
# ... then Verify sending the output to a file
# Verify sending the output to a file
go build
RESULT="$(mktemp)"
@ -34,5 +30,9 @@ if ./moar does-not-exist >& /dev/null ; then
exit 1
fi
# Ensure we can cross compile
GOOS=linux GOARCH=386 go build
GOOS=darwin GOARCH=amd64 go build
echo
echo "All tests passed!"