查找给定文本中的所有选定单词

我有下面的代码,我希望用户输入一些关键词,然后从这些词中找到给定字符串中存在的内容,但结果matches切片是一个长度等于要检查的文本的空切片 游乐场


package main


import (

    "fmt"

    "regexp"

)


func main() {

    p := []string{}

    p = append(p, "engineer")

    p = append(p, "doctor")

    var skills string

    for _, z := range p {

        skills += `|` + z

    }

    fmt.Println(skills)

    re := regexp.MustCompile(`(?i)` + skills)


    matches := re.FindAllString("I'm an engineer not a doctor", -1)

    fmt.Println(matches)

    for i, j := range matches {

        fmt.Println(i, j)

    }

}


幕布斯7119047
浏览 78回答 1
1回答

阿波罗的战车

感谢提供的评论,我得到的是:package mainimport (    "fmt"    "regexp"    "strings")func main() {    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)    matches := re.FindAllString("I'm an engineer not a doctor who is getting chemical permits", -1)    fmt.Println(matches, len(matches))    for i, j := range matches {        fmt.Println(i, j)    }}输出是:engineer|doctor|chemical (permit)[engineer doctor chemical permit] 30 engineer1 doctor2 chemical permit
打开App,查看更多内容
随时随地看视频慕课网APP