Search code examples
regexvisual-studio-coderegex-lookaroundsregex-group

How do I match the following with regex?


Title1
......

Title2: Description
...................

Title3
......

I am trying to match Title1, Description and Title3. Using (?<=: )(.*)(?=\n\.), I can match the Description. I couldn't figure how to match Title1, Description and Title3 together.


Solution

  • In VSCode, you can match the strings by finding the start of the whole file or the colon followed with a whitespace:

    (?<=:\s|^(?![^:\n]*:)).*(?=\n\.)
    

    See the demo screenshot:

    enter image description here

    Details:

    • (?<= - start of a positive lookbehind (that requires its pattern to match the text immediately to the left of the current location):
      • :\s - a colon and a whitespace
      • | - or
      • ^(?![^:\n]*:) - start of the line that has no : after any zero or more chars other than : and line break chars
    • ) - end of the lookbehind
    • .* - the rest of the line
    • (?=\n\.) - a positive lookahead that requires a line break and a . to appear immediately to the right of the current location.

    See the regex demo.