Search code examples
regexstringgo

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.


Solution

  • 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.