1

Regex matching multiple lines multiple times

\s*([^:]+?)\s*:\s*(.*(?:\s*(?!.*:).*)*)\s* 

This solution matches the date and time string.

How do I modify the above solution so that the date and time is included with the Description: header?

Name: John Doe

Age: 23

Primary Language: English

Description: This is a multiline
description field that I want 
to capture Fri, 02 Sep 2022 14:46:45 -0500

Country: Canada

1 Answer 1

1

One option could be to exclude matching a comma in the first part before the colon:

^([^,:\n\r]+):(.*(?:\R(?![^,:\n\r]+:).*)*)

Regex demo

Another option could be asserting that the next lines to match do not contain only a single colon:

^([^:\n\r]+):(.*(?:\R(?![^:\n\r]+:[^:\n\r]*$).*)*)

Explanation

  • ^ Start of string
  • ([^:\n\r]+) Capture group 1, match 1+ chars other than : or a newline
  • : Match literally
  • ( Capture group 2
    • .* Match the rest of the line
    • (?: Non capture group
      • \R Match any unicode newline sequence
      • (?![^:\n\r]+:[^:\n\r]*$) Assert that the line does not contain a single occurrence of :
      • .* Match the whole line
    • )* Close the non capture group and optionally repeat it to match all lines
  • ) Close group 2

See a regex demo and a PHP demo.

Sign up to request clarification or add additional context in comments.

3 Comments

The first solution worked great. The second option returned two matches. using php preg_match_all() Array ( [0] => Name: John Doe Age: 23 Primary Language: English Description: This is a multiline description field that I want to capture Fri, 02 Sep 2022 14:46:45 -0500 [1] => Country: Canada )
@MarcusCarey The second solution gets all the capture groups right? See regex101.com/r/Bs1G8w/1 and 3v4l.org/KiM8S
Yes the demo work. However, when I use it in a php script it returns 2 matches. The first solution works in a script. Thanks for the solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.