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
+7.8k Yum Error: no such table: packages
+6.9k Javascript : How to check a browser's Do Not Track status?
+20.6k Golang : Setting up/configure AWS credentials with official aws-sdk-go
+37.9k Golang : Remove dashes(or any character) from string
+5.7k Golang : How to setup a disk space used monitoring service with Telegram bot
+9.2k Fix ERROR 1045 (28000): Access denied for user 'root'@'ip-address' (using password: YES)
+42.7k Golang : Use wildcard patterns with filepath.Glob() example
+5.7k Golang : When to use make or new?
+24.7k Mac/Linux and Golang : Fix bind: address already in use error
+3.6k Adding Skype actions such as call and chat into web page examples
+8.5k Golang : Accessing content anonymously with Tor
+4.1k Golang : Print instead of building pyramids