Find all selected words in a given text

I’ve the below code, where I want the user to enter some key words, them find what from these words are exisiting in a given string, but the resulting matches sliceis an empty slice of a length equal to text to be checked
playground

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)
	}
}
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 + "|"
	}
	if len(skills) > 0 {
		skills = skills[:len(skills)-1]
	}
	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)
	}
}

https://play.golang.org/p/G0eJK8HEXxw

engineer|doctor
[engineer doctor]
0 engineer
1 doctor
1 Like

Thanks a lot, so my mistake is in using the seperator '|' in the begining of skills!

I am only learning myself, but i guess that problem in joining your words with ‘|’ you should have spaces between words. Though you could try 'z + " |" '.

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)
	}
}

Not true. It’s an ERE (Extended Regular Expression). Also, for any set A, the empty set is a subset of A.

1 Like

Thanks! I should probably learn some basics before making assumptions)