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
+16.8k Golang : Display list of time zones with GMT
+3.7k Mac OSX : Get disk partitions' size, type and name
+4.8k Unix/Linux : How to open tar.gz file ?
+23.6k Golang : Get current file path of a file or executable
+13.5k Golang : Rename directory
+22.4k Golang : Use regular expression to validate domain name
+9.4k Golang : ISO8601 Duration Parser example
+8.9k Golang : Edge detection with Sobel method
+9.4k Golang : Simple File Server
+12.1k Golang : Read XML elements data with xml.CharData example
+6.3k Golang : Dealing with postal or zip code example
+5.8k Mac/Linux/Windows : Get CPU information from command line