Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case insensitive HasSuffix in Go

I am looking for specific file types from a directory listing and use HasSuffix to do the comparision looking for a few specific file types. I would like to make this comparison case insensitive.

Is there a way to add EqualFold or another case insensitive comparison to the HasSuffix function?

like image 600
Adam Mayer Avatar asked Dec 14 '22 21:12

Adam Mayer


2 Answers

You could just use

if strings.HasSuffix(strings.ToLower(s), "suffix") {
    // do something 
}

You can also write your own wrapper function:

func hasSuffix(s, suffix string, caseSensitive bool) bool {
    if caseSensitive {
        return strings.HasSuffix(s, suffix)
    }
    return strings.HasSuffix(strings.ToLower(s), suffix)
}

For file names or paths you can use (see answer of PeterSO):

if strings.ToLower(filepath.Ext(s)) == ".fileending" {
    // do something
}
like image 168
TehSphinX Avatar answered Jan 11 '23 17:01

TehSphinX


"I am looking for specific file types from a directory listing. I would like to make this comparison case insensitive."

For example,

package main

import (
    "fmt"
    "io/ioutil"
    "os"
    "path/filepath"
    "strings"
)

func hasExts(path string, exts []string) bool {
    pathExt := strings.ToLower(filepath.Ext(path))
    for _, ext := range exts {
        if pathExt == strings.ToLower(ext) {
            return true
        }
    }
    return false
}

func main() {
    dir := `./`
    files, err := ioutil.ReadDir(dir)
    if err != nil {
        fmt.Fprintln(os.Stderr, err)
        return
    }
    sourceExts := []string{".go", ".Py", ".c", ".cpp"}
    for _, fi := range files {
        if hasExts(fi.Name(), sourceExts) {
            fmt.Println(fi.Name())
        }
    }
}

Output:

t.c
t.go
t.py
t1.go
t1.py
t2.go

For a special form of strings.HasSuffix start by copying the code from the strings package.

func HasSuffix(s, suffix string) bool {
    return len(s) >= len(suffix) && s[len(s)-len(suffix):] == suffix
}

Then modify it to suit your purpose. For example,

func hasSuffix(s, suffix string) bool {
    return len(s) >= len(suffix) &&
        strings.ToLower(s[len(s)-len(suffix):]) == strings.ToLower(suffix)
}
like image 24
peterSO Avatar answered Jan 11 '23 18:01

peterSO