How do I match the following with regex?

Viewed 135
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.

2 Answers

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.

You might also assert not a : to the left, or assert that that string does not contain : and then match the whole line.

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

The pattern matches:

  • (?<= Positive lookbehind, assert to the left
    • : match :
    • | Or
    • ^(?!.*?: ) Negative lookahead, start of string and assert not : in the line
  • ) Close lookbehind
  • .* Match the whole line
  • (?=\n\.) Assert a newline and .

Regex demo

enter image description here

Related