正则匹配文件中的中文并输出到文件
by Wardon posted on 2020年5月28日 14:18 under 技术分享
标签: Go
package main
import (
"bufio"
"fmt"
"io"
"io/ioutil"
"os"
"regexp"
"strings"
)
var targetDir = "D:\\workspace\\php\\mytrans\\themes\\config\\plugins\\"
var message = []string{}
func main() {
f, err := os.OpenFile("result.txt", os.O_CREATE|os.O_RDWR, 0777)
if err != nil {
panic(err)
}
defer f.Close()
searchChinese(targetDir)
for _, msg := range message {
f.WriteString(msg)
}
}
func searchChinese(path string) {
rd, err := ioutil.ReadDir(path)
if err != nil {
panic(err)
}
for _, fileInfo := range rd {
if fileInfo.IsDir() {
searchChinese(path + fileInfo.Name() + "\\")
} else {
if strings.Index(path+fileInfo.Name(), "forms") != -1 && fileInfo.Name() != "forms.php" {
regx, err := regexp.Compile("[\u4e00-\u9fa5]+.*?[\u4e00-\u9fa5]")
if err != nil {
panic(err)
}
fi, err := os.Open(path + fileInfo.Name())
if err != nil {
panic(err)
}
defer fi.Close()
br := bufio.NewReader(fi)
var i = 1
for {
line, _, err := br.ReadLine()
if err == io.EOF {
break
}
strs := regx.FindAllString(string(line), -1)
for _, str := range strs {
c := fmt.Sprintf("filename: %v, line: %v, result: %v\r\n", path+fileInfo.Name(), i, str)
message = append(message, c)
}
i++
}
}
}
}
}