Golang正则表达式FindAllString如何排除重复匹配
Golang正则表达式FindAllString如何排除重复匹配
以下代码用于读取根目录下的所有 txt 文件,根据给定的 regex 扫描其中的特定单词,并报告在每个文件中找到的 regex 中的单词。
我遇到的问题是,如果一个单词被多次提及(例如,在文件的不同位置),它将被报告多次,而我需要将其报告为唯一的,即排除重复项。例如,在 txt 文件中:
I'm an engineer not a doctor
really, I'm not a doctor
单词 doctor 被报告了两次,而我需要将其视为唯一,即只需知道它存在于文件中即可。
我的代码如下:
package main
import (
"fmt"
"io/ioutil"
"log"
"path/filepath"
"regexp"
"strings"
)
func main() {
files, err := ioutil.ReadDir(".")
if err != nil {
log.Fatal(err)
}
p := []string{}
p = append(p, "engineer")
p = append(p, "doctor")
p = append(p, "chemical (permit)")
skills := strings.Join(p, "|")
fmt.Println(skills)
re := regexp.MustCompile(`(?i)` + skills)
for _, file := range files {
if strings.ToLower(filepath.Ext(file.Name())) == ".txt" {
fmt.Println(file.Name())
b, err := ioutil.ReadFile(file.Name()) // just pass the file name
if err != nil {
fmt.Print(err)
}
//fmt.Println(b) // print the content as 'bytes'
str := string(b) // convert content to a 'string'
matches := re.FindAllString(str, -1)
fmt.Println(matches, len(matches))
for _, j := range matches {
fmt.Println(j)
}
}
}
}
更多关于Golang正则表达式FindAllString如何排除重复匹配的实战教程也可以访问 https://www.itying.com/category-94-b0.html
2 回复
你至少可以将结果放入映射(map)中并对其进行操作。
更多关于Golang正则表达式FindAllString如何排除重复匹配的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
要排除重复匹配,可以使用map来存储已找到的单词。以下是修改后的代码:
package main
import (
"fmt"
"io/ioutil"
"log"
"path/filepath"
"regexp"
"strings"
)
func main() {
files, err := ioutil.ReadDir(".")
if err != nil {
log.Fatal(err)
}
p := []string{}
p = append(p, "engineer")
p = append(p, "doctor")
p = append(p, "chemical (permit)")
skills := strings.Join(p, "|")
fmt.Println(skills)
re := regexp.MustCompile(`(?i)` + skills)
for _, file := range files {
if strings.ToLower(filepath.Ext(file.Name())) == ".txt" {
fmt.Println(file.Name())
b, err := ioutil.ReadFile(file.Name())
if err != nil {
fmt.Print(err)
}
str := string(b)
matches := re.FindAllString(str, -1)
// 使用map去重
uniqueMatches := make(map[string]bool)
for _, match := range matches {
uniqueMatches[strings.ToLower(match)] = true
}
// 将去重后的结果转换回切片
var uniqueList []string
for match := range uniqueMatches {
uniqueList = append(uniqueList, match)
}
fmt.Println(uniqueList, len(uniqueList))
for _, j := range uniqueList {
fmt.Println(j)
}
}
}
}
或者,如果你需要保持原始大小写但只去重不区分大小写,可以这样修改:
// 使用map记录已出现的小写形式
seen := make(map[string]bool)
var uniqueMatches []string
for _, match := range matches {
lower := strings.ToLower(match)
if !seen[lower] {
seen[lower] = true
uniqueMatches = append(uniqueMatches, match)
}
}
fmt.Println(uniqueMatches, len(uniqueMatches))
for _, j := range uniqueMatches {
fmt.Println(j)
}
这样修改后,即使文件中多次出现"doctor",也只会被报告一次。

