0

How to force regex to match for optional groups at the beginning and the end of the regex. Example:

(keyword1)*\W*(?:\w+\W+){0,6}(keyword2)\W*(?:\w+\W+){0,6}(keyword3)*

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 Go Playground:

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

Thanks

David
  • 311
  • 1
  • 4
  • 14
  • It is impossible to achieve with 1 Go regex. You will have to use `(keyword1)*\W*(?:\w+\W+){0,6}(keyword2)\W*(?:\w+\W+){0,6}(keyword3)*` and then add more programming logic. – Wiktor Stribiżew Nov 26 '16 at 15:35
  • You mean adding programming logic to remove extra strings? – David Nov 26 '16 at 15:41
  • Something should be added to perform additional checks. Another way is to make the `keyword1` and `keyword3` obligatory in 2 alternatives, `(keyword1)\W*(?:\w+\W+){0,6}(keyword2)\W*(?:\w+\W+){0,6}(keyword3)*|(keyword1)*\W*(?:\w+\W+){0,6}(keyword2)\W*(?:\w+\W+){0,6}(keyword3)`, but still it will require "manual" work later. – Wiktor Stribiżew Nov 26 '16 at 15:47
  • Someone had the pretty same question here: http://stackoverflow.com/questions/23968992/how-to-match-a-regex-with-backreference-in-go Because you need to use backreferences for that. – Martin Cup Nov 27 '16 at 19:49

0 Answers0