package main import ( "regexp" "fmt" ) func main() { input := "The quick brown fox jumps over the lazy dog" re := regexp.MustCompile(`\bfox\b`) // match whole word "fox" pos := re.FindIndex([]byte(input)) fmt.Printf("Found 'fox' at position %d to %d\n", pos[0], pos[1]) }
Found 'fox' at position 16 to 19
package main import ( "regexp" "fmt" ) func main() { input := "The quick brown fox jumps over the lazy dog" re := regexp.MustCompile(`\b\w{5}\b`) // match any 5 letter word positions := re.FindAllIndex([]byte(input), -1) for i, pos := range positions { fmt.Printf("Match %d found at position %d to %d\n", i+1, pos[0], pos[1]) } }
Match 1 found at position 4 to 9 Match 2 found at position 16 to 21 Match 3 found at position 25 to 30 Match 4 found at position 36 to 41In this example, we use Regexp FindAllIndex to find the position of all 5-letter words in the input string. We use the \w escape sequence to match any word character and the {5} repetition quantifier to match exactly 5 characters. Package library: go regexp