user2737876
user2737876

Reputation: 1168

Golang Regex extract text between 2 delimiters - including delimiters

As stated in the title I have an program in golang where I have a string with a reoccurring pattern. I have a beginning and end delimiters for this pattern, and I would like to extract them from the string. The following is pseudo code:

string := "... This is preceding text
PATTERN BEGINS HERE (
pattern can continue for any number of lines...
);
this is trailing text that is not part of the pattern"

In short what I am attempting to do is from the example above is extract all occurrences of of the pattern that begins with "PATTERN BEGINS HERE" and ends with ");" And I need help in figuring out what the regex for this looks like.

Please let me know if any additional info or context is needed.

Upvotes: 2

Views: 5918

Answers (2)

logi-kal
logi-kal

Reputation: 7880

The regex is:

(?s)PATTERN BEGINS HERE.*?\);

where (?s) is a flag to let .* match multiple lines (see Go regex syntax – EDIT: the URL is now broken, here the archived version).

See a demo here.

Upvotes: 5

Andre Romano
Andre Romano

Reputation: 1012

Not regex, but works

func findInString(str, start, end string) ([]byte, error) {
    var match []byte
    index := strings.Index(str, start)

    if index == -1 {
        return match, errors.New("Not found")
    }

    index += len(start)

    for {
        char := str[index]

        if strings.HasPrefix(str[index:index+len(match)], end) {
            break
        }

        match = append(match, char)
        index++
    }

    return match, nil
}

EDIT: Best to handle individual character as bytes and return a byte array

Upvotes: 3

Related Questions