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
+8.2k Golang : Ackermann function example
+7.1k Android Studio : How to detect camera, activate and capture example
+14.2k Golang : GUI with Qt and OpenCV to capture image from camera
+33.5k Golang : convert(cast) bytes to string
+8.5k Golang : Gorilla web tool kit schema example
+10.2k Android Studio : Simple input textbox and intercept key example
+6k Apt-get to install and uninstall Golang
+7.6k Swift : Convert (cast) String to Double
+12k Golang : Encrypt and decrypt data with x509 crypto
+8.6k Golang : Take screen shot of browser with JQuery example
+4.8k Linux : How to set root password in Linux Mint
+5.1k Javascript : Shuffle or randomize array example