Find all strings in between two strings in Go

Viewed 2650

I am working on extracting mutliple matches between two strings.

In the example below, I am trying to regex out an A B C substring out of my string.

Here is my code:

package main
    
import (
    "fmt"
    "regexp"
)
    
func main() {
    str:= "Movies: A B C Food: 1 2 3"
    re := regexp.MustCompile(`[Movies:][^Food:]*`)
    match := re.FindAllString(str, -1)
    fmt.Println(match)
}

I am clearly doing something wrong in my regex. I am trying to get the A B C string between Movies: and Food:.

What is the proper regex to get all strings between two strings?

1 Answers

In Go, since its RE2-based regexp does not support lookarounds, you need to use capturing mechanism with regexp.FindAllStringSubmatch function:

left := "LEFT_DELIMITER_TEXT_HERE"
right := "RIGHT_DELIMITER_TEXT_HERE"
rx := regexp.MustCompile(`(?s)` + regexp.QuoteMeta(left) + `(.*?)` + regexp.QuoteMeta(right))
matches := rx.FindAllStringSubmatch(str, -1)

Note the use of regexp.QuoteMeta that automatically escapes all special regex metacharacters in the left- and right-hand delimiters.

The (?s) makes . match across lines and (.*?) captures all between ABC and XYZ into Group 1.

So, here you can use

package main

import (
    "fmt"
    "regexp"
)

func main() {
    str:= "Movies: A B C Food: 1 2 3"
    r := regexp.MustCompile(`Movies:\s*(.*?)\s*Food`)
    matches := r.FindAllStringSubmatch(str, -1)
        for _, v := range matches {
            fmt.Println(v[1])
        }   
}

See the Go demo. Output: A B C.

Related