GO语言如何判断字符串中是否包含有某个单词,同时忽略大小写?!

通过分析可以知道,不能简单的通过是否包含字符串来判断,例如: 字符串“kiss goodbye”,虽然是有包含good,但是并不是我们要的匹配,单词的前和后是有空格或是换行隔开,或是没有任何东西,对应的正则表达式如下:

`(^|([\s\t\n]+))(good)($|([\s\t\n]+))`

(^|([\s\t\n]+)): good开头或是前面是空白、换行、tab分隔

($|([\s\t\n]+)):good结尾或是后面是空白、换行、tab分隔

如果需要忽略大小写,则加上 (?i),所以最终正则表达式如下:

(?i)(^|([\s\t\n]+))(good)($|([\s\t\n]+))

例子:

package main
 
import (
	"fmt"
	"regexp"
)
 
func main() {
	matchWard:= "good"
	var s1 = `good`
	var s2 = `you good !`
	var s3 = `ss good`
	var s4	 = `kiss goodby`
	reg := regexp.MustCompile(`(?i)(^|([\s\t\n]+))(` +matchWard+`)($|([\s\t\n]+))`)
	fmt.Println(reg.MatchString(s1)) // true
	fmt.Println(reg.MatchString(s2)) // true
	fmt.Println(reg.MatchString(s3)) // true
	fmt.Println(reg.MatchString(s4)) // false
}