Search code examples
regexsublimetext3regex-lookarounds

What regex produces the result between 2 pattern rows?


Briefly

I am trying to set up Sublime Text 4 to hide regions in code. To do this, I use the AutoFold extension, which can fold code fragments according to specified regular expressions. I need a regex that will give content between 2 lines, where the first one contains #region and the last one contains #endregion.

Closer to the subject:

There is a piece of code:

-- #region NAME 1
line 1
line 2
-- #endregion

line 3

-- #region NAME 2
line 4
line 5
-- #endregion

I want to get the result as shown in the picture

desired result

For demonstration, I am using 2 regexes (?<=-- #region NAME 1)(.|\n)*?(?=-- #endregion) and (?<=-- #region NAME 2)(.|\n)*?(?=-- #endregion).

Question

What should a regular expression look like that will give the same result?

How I tried:

  1. (?<=-- #region )(.|\n)*?(?=-- #endregion) gives a similar result, but it hides the region name, which doesn't suit me🙁
  2. (?<=\n)[^$]+ removes the beginning of the line before the first \n. It looks like something that, together with step 1, will solve my problem, but I can't put it together in a single expression🙁 I tried something like this:: (?<=-- #region )((?<=\n)[^$]+)(?=-- #endregion)
  3. ^.*#region.*\n gives a full line containing the region and name, but it is also impossible to compose with item 1 🙁 tried something like this: (?<=(^.*#region.*\n))(.|\n)*?(?=-- #endregion)

Solution

  • You can match the whole line with -- #region until the end. Then you can make use of \K to clear the match buffer and match until the first occurrence of -- #endregion

    -- #region .+\K[\s\S]*?(?=-- #endregion)
    

    Regex demo

    Taking newlines into account:

    -- #region .+\R\K[\s\S]*?\R(?=-- #endregion)
    

    Regex demo