为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
扬帆大鱼 2022-08-01 10:46:51
我有下面的代码,我希望用户输入一些关键字,然后从给定字符串中找到这些单词中存在的内容,但生成的切片是长度等于要检查的文本的空切片 playgroundmatchespackage mainimport (    "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)    }}
查看完整描述

1 回答

?
POPMUISE

TA贡献1765条经验 获得超5个赞

package main


import (

    "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] 3

0 engineer

1 doctor

2 chemical permit


查看完整回答
反对 回复 2022-08-01
  • 1 回答
  • 0 关注
  • 84 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信