Someone Random
Someone Random

Reputation: 45

Javascript - Match Regex for multiple lines

I want to match a regex like that:

[Intro]

E|------|---4-|
B|--3h5-|-----|
C|------|-----|
D|------|---3-|
G|-1----|-----|
E|------|--0--|

to get me those groups:

Group1: Intro
Group2: E
Group3: ------|---4-|
Group4: B
Group5: --3h5-|-----|
Group6: C
Group7: ------|-----|
etc until the last line

There are always six lines. Now, I got to a point where this pattern:

((?:\w|\s|b|#|m){1,2})\|((?:(?:\d|\w|-|\/|^|~|\\|\(|\))+\|)+)

return me this match for such string:

Match1:
Group1: E
Group2: ------|---4-|
Match2:
Group1: B
Group2: --3h5-|-----|

etc until last line

My question is, how can I match the regex to match only exactly six line with one line break between each line (Maybe using the pattern I wrote and add line break at start or end or something)

And also how to get the [Intro] tag which is two linebreak away from the six lines?

Upvotes: 1

Views: 59

Answers (1)

Code Maniac
Code Maniac

Reputation: 37775

One way is :-

  • Split the string first by newline
  • Remove all the falsy values
  • map over array and replace undesired characters
  • flatten the array

let str = `[Intro]

E|------|---4-|
B|--3h5-|-----|
C|------|-----|
D|------|---3-|
G|-1----|-----|
E|------|--0--|`

let final = str.split('\n')
               .filter(Boolean)
               .map(v=> v.replace(/[\]\[]/g,'').match(/^[^|]+\||.+/g))
               .flat()

console.log(final)

Upvotes: 3

Related Questions