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
+22.9k Golang : untar or extract tar ball archive example
+11.6k Golang : Change date format to yyyy-mm-dd
+19.4k Golang : Get RGBA values of each image pixel
+10.2k Golang : Edge detection with Sobel method
+36.5k Golang : How to split or chunking a file to smaller pieces?
+5.3k Javascript : Change page title to get viewer attention
+14.5k Golang : How to filter a map's elements for faster lookup
+10.9k Golang : Sieve of Eratosthenes algorithm
+10k Golang : Convert octal value to string to deal with leading zero problem
+25.1k Golang : Create PDF file from HTML file
+11.7k Android Studio : Create custom icons for your application example
+25.3k Golang : Convert uint value to string type