Golang中如何提取包含指定关键词的字符串行
解决方案
问题分析
你的代码存在两个核心问题:
- 关键词设置为
enabled,但目标句子中仅包含enable,二者不匹配,导致无法提取到目标内容; - 正则表达式的标志位置和匹配逻辑有误,
(?i)应放在正则开头以全局启用不区分大小写匹配,且原正则的结尾匹配逻辑会导致结果冗余。
方案一:使用正则表达式提取
修正正则逻辑,同时调整关键词匹配规则(若需匹配enable及其变体如enabled,直接匹配enable即可,因为enabled包含该词根):
package main import ( "fmt" "regexp" ) func main() { s := "Their have a problem with the server.I have to continue the task.Hope the server will enable for everyone.Once enable then we will continue." val := "enable" // 若需严格匹配enabled则改回原关键词 // 正则:不区分大小写,匹配包含关键词的完整句子(以句号结尾) re := regexp.MustCompile(`(?i)[^.]*` + val + `[^.]*\.`) results := re.FindAllString(s, -1) for _, res := range results { fmt.Println(res) } }
方案二:分割字符串后遍历检查
若不需要复杂正则,可先按句号分割字符串,再逐个检查句子是否包含关键词(不区分大小写),逻辑更直观:
package main import ( "fmt" "strings" ) func main() { s := "Their have a problem with the server.I have to continue the task.Hope the server will enable for everyone.Once enable then we will continue." val := "enable" // 按句号分割成句子列表 sentences := strings.Split(s, ".") for _, sen := range sentences { // 去除空格并检查是否包含关键词(不区分大小写) trimmed := strings.TrimSpace(sen) if trimmed != "" && strings.Contains(strings.ToLower(trimmed), strings.ToLower(val)) { fmt.Println(trimmed + ".") } } }
两种方案都能提取出目标句子:
Hope the server will enable for everyone. Once enable then we will continue.
内容的提问来源于stack exchange,提问作者Navjot Sharma
相关产品推荐
相关产品推荐

