catmandx
catmandx

Reputation: 145

Regex for multiline matches

I have a format like this:

-Note1: Value is 02
-Note 2: Line 1
Line 2

When I do String replace with regex, i want it to group like this:

"Note1" "Value is 02"
"Note 2" "Line 1
Line 2" (the value for Note 2 spans 2 lines, which makes it "Line 1\nLine 2")

My current regex have this output:

"Note1" "Value is 02"
"Note 2" "Line 1" (and leave out Line 2)

Current regex:

/-(.*):(.*|\n*)/g

What can I do to achieve what I want?

Upvotes: 0

Views: 71

Answers (1)

MonkeyZeus
MonkeyZeus

Reputation: 20737

Since JavaScript does not support the Singleline (/s) flag you need to get creative:

/^-(.*?):(.*(?:[\r\n]+[^-].*)*)/gm
  • /^- - start with a dash
  • (.*?): - capture everything which is not a colon into group 1
  • (.* - start group 2 and capture everything
  • (?:[\r\n]+[^-].*)* - if a newline is detected and the line does not start with a dash then capture the entire line into group 2; repeat zero or more times as needed
  • ) - close group 2
  • /gm - global and multiline flags

https://regex101.com/r/3YW3Mg/1

Upvotes: 1

Related Questions