Golang : Match strings by wildcard patterns with filepath.Match() function
Problem:
You want to match strings using the same wildcard patterns commonly used in Linux/Unix shells such as *.go
or *data[0-9]*
. How to do that?
Solution:
package main
import (
"fmt"
"path/filepath"
)
func main() {
filename := "start.txt"
pattern := "*art*"
matched, err := filepath.Match(pattern, filename)
if err != nil {
fmt.Println(err)
}
fmt.Println(matched)
//---------------------------------
pattern = "*fart*"
matched, err = filepath.Match(pattern, filename)
if err != nil {
fmt.Println(err)
}
fmt.Println(matched)
//---------------------------------
filename = "data123.csv"
pattern = "data[0-9]*"
matched, err = filepath.Match(pattern, filename)
if err != nil {
fmt.Println(err)
}
fmt.Println(matched)
}
Output :
true
false
true
NOTES: This example is for matching strings. For filenames in the current or specific directory. See this tutorial https://socketloop.com/tutorials/golang-use-wildcard-patterns-with-filepath-glob-example
It should work as well if you replace filepath.Match()
with path.Match()
Reference:
See also : Golang : Use wildcard patterns with filepath.Glob() example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+4.6k Which content-type(MIME type) to use for JSON data
+18.5k Unmarshal/Load CSV record into struct in Go
+52.1k Golang : How to get struct field and value by name
+15.8k Golang : How to reverse elements order in map ?
+5.7k Golang : Detect variable or constant type
+5.5k Golang : Frobnicate or tweaking a string example
+6.6k Default cipher that OpenSSL used to encrypt a PEM file
+29k Golang : Saving(serializing) and reading file with GOB
+12.1k Golang : How to display image file or expose CSS, JS files from localhost?
+15.3k Golang : Force download file example
+20.5k PHP : Convert(cast) int to double/float
+7.2k Golang : Check to see if *File is a file or directory