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
+5.9k Golang : List all packages and search for certain package
+6.4k Golang : Detect face in uploaded photo like GPlus
+7.6k SSL : How to check if current certificate is sha1 or sha2 from command line
+7.4k Golang : Accessing dataframe-go element by row, column and name example
+27.5k Golang : Convert integer to binary, octal, hexadecimal and back to integer
+5.8k Linux/Unix/PHP : Restart PHP-FPM
+27.6k Golang : dial tcp: too many colons in address
+8.2k Golang : How To Use Panic and Recover
+10.7k Golang : Simple File Server
+6.6k Golang : How to validate ISBN?
+7.8k Golang : Regular Expression find string example
+9.3k Golang : Temperatures conversion example