如何以“不区分大小写”的方式在文件中搜索单词?
例如如果我在文件中搜索
UpdaTe
,如果文件包含更新,搜索应该选择它并将其计为匹配项。
strings.EqualFold()
可以检查两个字符串是否相等,同时忽略大小写。它甚至可以与 Unicode 配合使用。请参阅
http://golang.org/pkg/strings/#EqualFold了解更多信息。 http://play.golang.org/p/KDdIi8c3Ar
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.EqualFold("HELLO", "hello"))
fmt.Println(strings.EqualFold("ÑOÑO", "ñoño"))
}
两者都返回 true。
strings.Contains
当前的答案都不正确,除非您只搜索
少数语言(如英语)没有某些分音符/元音变音或其他unicode字形修饰符(更“正确”的方式来定义它,如所提到的@折断)。标准的谷歌短语是“搜索非 ASCII 字符”。
为了正确支持语言搜索,您需要使用
。
func SearchForString(str string, substr string) (int, int) {
m := search.New(language.English, search.IgnoreCase)
return = m.IndexString(str, substr)
}
start, end := SearchForString('foobar', 'bar');
if start != -1 && end != -1 {
fmt.Println("found at", start, end);
}
或者如果您只想要起始索引:
func SearchForStringIndex(str string, substr string) (int, bool) {
m := search.New(language.English, search.IgnoreCase)
start, _ := m.IndexString(str, substr)
if start == -1 {
return 0, false
}
return start, true
}
index, found := SearchForStringIndex('foobar', 'bar');
if found {
fmt.Println("match starts at", index);
}
在此处搜索
language.Tag
结构
以查找您想要搜索的语言,或者如果您不确定,请使用
language.Und
。更新
package main
import (
"fmt"
"strings"
"golang.org/x/text/language"
"golang.org/x/text/search"
)
var s = `Æ`
var s2 = `Ä`
func main() {
m := search.New(language.Finnish, search.IgnoreDiacritics)
fmt.Println(m.IndexString(s, s2))
fmt.Println(CaseInsensitiveContains(s, s2))
}
// CaseInsensitiveContains in string
func CaseInsensitiveContains(s, substr string) bool {
s, substr = strings.ToUpper(s), strings.ToUpper(substr)
return strings.Contains(s, substr)
}
//create a regex `(?i)update` will match string contains "update" case insensitive
reg := regexp.MustCompile("(?i)update")
f, err := os.Open("test.txt")
if err != nil {
log.Fatal(err)
}
defer f.Close()
//Do the match operation
//MatchReader function will scan entire file byte by byte until find the match
//use bufio here avoid load entire file into memory
println(reg.MatchReader(bufio.NewReader(f)))