Examples of regular expression search capabilities in go language files
- 2020-06-01 10:02:11
- OfStack
This article illustrates the regular expression search for go language files as an example. I will share it with you for your reference as follows:
package main
import (
"fmt"
"os"
"path/filepath"
"regexp"
)
func main() {
// Command line argument
args := os.Args
// Check the parameters
if len(args) == 1 {
fmt.Println("ff is a file find tool. use like bottom")
fmt.Println("ff [dir] [regexp]")
return
}
if len(args) < 3 {
fmt.Println("args < 3")
return
}
fileName := args[1]
pattern := args[2]
file, err := os.Open(fileName)
if err != nil {
fmt.Println(err)
return
}
fi, err := file.Stat()
if err != nil {
fmt.Println(err)
return
}
if !fi.IsDir() {
fmt.Println(fileName, " is not a dir")
}
reg, err := regexp.Compile(pattern)
if err != nil {
fmt.Println(err)
return
}
// Directory traversal
filepath.Walk(fileName,
func(path string, f os.FileInfo, err error) error {
if err != nil {
fmt.Println(err)
return err
}
if f.IsDir() {
return nil
}
// Match the directory
matched := reg.MatchString(f.Name())
if matched {
fmt.Println(path)
}
return nil
})
}
PS: here are two more handy regular expression tools for you to use:
JavaScript regular expression online testing tool:
http://tools.ofstack.com/regex/javascript
Online regular expression generation tool:
http://tools.ofstack.com/regex/create_reg
I hope this article has been helpful to you in the programming of Go language.