Emin TAYFUR
Emin TAYFUR

Reputation: 136

Javascript Regex multiple search in two words

I want to transfer the results between Regex and two words to an array, but unfortunately I couldn't this. Can you help me?

In this text

[row]
Row text1
[rowEnd]

[row]
Row text2
[rowEnd]

I will search this content,

[row]
(.*)
[rowEnd]

Based on this I write a regex like this

/(\[row\]+)(.*)(\[rowEnd\])/gs

However, this way, it takes the whole, not piece by piece.

Thank you in advance for your help.

Upvotes: 0

Views: 572

Answers (2)

Som Shekhar Mukherjee
Som Shekhar Mukherjee

Reputation: 8168

Without RegEx

  • Split the data by "[row]".
  • Then filter those strings which end with "[rowEnd]".
  • Finally remove "[rowEnd]" from the filtered strings.

const 
  data = "[row]Row text1[rowEnd][row]Row text2[rowEnd]",
  res = data
    .split("[row]")
    .filter((s) => s.endsWith("[rowEnd]"))
    .map((s) => s.slice(0, -8));

console.log(res);

Upvotes: 1

The fourth bird
The fourth bird

Reputation: 163217

In Javascript, you could use

^\[row]\r?\n([^]*?)\r?\n\[rowEnd]
  • ^ Start of string
  • \[row]\r?\n Match [row] and a newline
  • ( Capture group 1
    • [^]*? Match 0+ times any char including a newline non greedy
  • ) Close group 1
  • \r?\n\[rowEnd] Match a newline and [rowEnd]

Regex demo

const regex = /^\[row]\r?\n([^]*?)\r?\n\[rowEnd]/gm;
const str = `[row]
Row text1
[rowEnd]

[row]
Row text2
[rowEnd]`;

Array.from(str.matchAll(regex), m => console.log(m[1]));

Upvotes: 4

Related Questions