2

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.

2 Answers 2

5

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.

3

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.