Split blocks of data with the same title using regex

Issue

I have a long string that is build like that:

[[title]]
a = "1"
b = "1"
c = "1"
d = "1"
e = [
 "1",
 "1",
]

[[title]]
a = "2"
b = "2"
c = "2"
d = "2"
e = [
 "2",
]

[[title]]
a = "a3"
b = "3"
c = "3"

[[title]]
a = "a4"
b = "4"
c = "4"
e = [
 "4",
]

My target is to extract the text inside each title (without the title) and put it into a slice.
I’ve tried to use the attributes keys (like d and e) but sometimes they don’t exist.

You can look in my regex below:

(?m)(((\[\[title]]\s*\n)(?:^.+$\n)+?)(d.*?$)(\s*e(.|\n)*?])?)

I want to find a way to extract the data between each title until \n or end of string

Edition:

I’m using GO so I can’t use look around \ behind syntax

Thanks!

Solution

You can use the following pattern that matches from [[title]] to an empty line.

`\[\[title]](.*?)^$`gms

Explanation

  • \[\[title]] Match [[title]]
  • ( Capturing group
    • .*? Non-greedy match till next match
  • ) Close group
  • ^$ Using m (multiline) flag this means an empty line

See the demo with the Golang regex engine

Answered By – Artyom Vancyan

Answer Checked By – Gilberto Lyons (GoLangFix Admin)

Leave a Reply

Your email address will not be published.