Forcing regex to match exactly optional group at the start and the end of the regex
<p>How to force regex to match for optional groups at the beginning and the end of the regex. Example:</p>

<p><code>(keyword1)*\W*(?:\w+\W+){0,6}(keyword2)\W*(?:\w+\W+){0,6}(keyword3)*</code></p>

<p>Here keyword1 and keywrod3 are at the start and the end of the regex respectively and are optional. I am looking for keyword1, keyword2 and keyword3 in this order.We can have up to 6 words between keywords but the matched string should start by one keyword and end by one of the keywords. No extra string is needed. Is there a way to do that. Any suggestion is welcome. Here is a code and a link to <a href="https://play.golang.org/p/h5mXISPCk8" rel="nofollow noreferrer">Go Playground</a>:</p>

<pre><code>package main

import (
    "fmt"
    "regexp"
)

func main() {
    //here ok as exact match. The matched string starts by one of the keyword and ends by one of them. 
    re := regexp.MustCompile(`(keyword1)\W*(?:\w+\W+){0,6}(keyword2)\W*(?:\w+\W+){0,6}(keyword3)`)
    text := "start text keyword1 optional word here then keyword2 again optional words then keyword3 others words after."
        s := re.FindAllString(text, -1)
    fmt.Println(s)

    //Here not exact match as the result doesn't start by keyword1 and end by keyword3
    re = regexp.MustCompile(`(keyword1)*\W*(?:\w+\W+){0,6}(keyword2)\W*(?:\w+\W+){0,6}(keyword3)*`)
    text = "start text keyword1 optional word then keyword2 optional words keyword3 others words after."
    s = re.FindAllString(text, -1)
    fmt.Println(s)
}
</code></pre>

<p>Thanks</p>