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
+11.3k Golang : Concurrency and goroutine example
+13.2k Golang : Qt progress dialog example
+10.7k Golang : Create Temporary File
+6.2k Grep : How to grep for strings inside binary data
+10.6k PHP : Convert(cast) bigInt to string
+10.8k Golang : Proper way to test CIDR membership of an IP 4 or 6 address example
+9.7k CodeIgniter : Load different view for mobile devices
+5.5k Unix/Linux : Get reboot history or check when was the last reboot date
+15.2k Golang : Force download file example
+23.4k Golang : Fix type interface{} has no field or no methods and type assertions example
+9.5k Golang : ffmpeg with os/exec.Command() returns non-zero status
+6.8k Javascript : How to get JSON data from another website with JQuery or Ajax ?