Uzma
Uzma

Reputation: 45

Regex to match between two lines

I am trying to create a regex for a block of string which is dynamic. The dynamic data which I receive has the below format:

[Begin] some text goes here.\r\n[Begin] {\r\n[Begin] stage\r\n[Begin] { (dynamicName1)\r\nRandom text here\r\nRandom line2 text\r\nAnd still keeps going\r\n[Begin] }\r\n[Begin] stage\r\n[Begin] { (dynamicName2)\r\nStage dynamicName2 skipped\r\n[Begin] }\r\n

Looking to extract the string which is between the pattern as shown below:

[Begin] { (dynamicName1)\r\n/*trying to extract this data\r\n//which is available here*/\r\n[Begin] }

The pattern I am using is doing half the job but isn't precise in the result. My result also has the dynamicName1) line which I need to skip. Trying with these patterns

Pattern 1 - /\[Begin\]\s*{\s*\((\w+(?=\))[\S\s]*?)\[Begin\]\s*}/g
Pattern 2 - /\[Begin\]\s*{\s*\(([\S\s]*?)\[Begin\]\s*}/g

Am I missing something?

Upvotes: 2

Views: 1214

Answers (2)

wp78de
wp78de

Reputation: 18990

Here we go. I suggest the following pattern:

\[Begin\]\s+{\s+\([^()]+\)(.+?)\[Begin\]\s+}

Demo, Sample Code:

const regex = /\[Begin\]\s+{\s+\([^()]+\)(.+?)\[Begin\]\s+}/gm;
const str = `[Begin] some text goes here.\\r\\n[Begin] {\\r\\n[Begin] stage\\r\\n[Begin] { (dynamicName1)\\r\\nRandom text here\\r\\nRandom line2 text\\r\\nAnd still keeps going\\r\\n[Begin] }\\r\\n[Begin] stage\\r\\n[Begin] { (dynamicName2)\\r\\nStage dynamicName2 skipped\\r\\n[Begin] }\\r\\n`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    console.log(`Match: ${m[1]}`);
}

Upvotes: 1

Jan
Jan

Reputation: 43189

You could make use of a capturing groups and anchors:

^\[Begin\]\s+\{\s+\([^()]*\)\s+([\s\S]+?)^\[Begin\][ \t]+}

Verbosely:

^\[Begin\]            # [Begin] at the beginning of a line
\s+\{\s+\([^()]*\)\s+ # require { and ()
([\s\S]+?)            # capture anything including newlines lazily
^\[Begin\]\s+}        # up to [Begin] }

See a demo on regex101.com (and mind the multiline mode).

Upvotes: 2

Related Questions