Home > Net >  Capture line breaks in subgroups
Capture line breaks in subgroups

Time:03-30

I thought I had an easy situation but somehow I can not figure out the right RegEx to do so.

Let us say I have text seperated on 3 different new lines like:

ABC
DEF
GHI

And I want to capture each line in a seperate group, but the regex should be able to match 1 ore more new lines.

Possible expected outcome from the RegEx is:

$0 : ABC
     BCD
     GHI
$1 : ABC
$2 : BCD
$3 : GHI

or in case theres only ABC with no follow up new lines

$0 : ABC
$1 : ABC

or in case theres 5 new lines

$0 : ABC
     BCD
     GHI
     JKL
     MNO
$1 : ABC
$2 : BCD
$3 : GHI
$4 : JKL
$5 : MNO

Would someone be able to produce a RegEx that would solve this question?

CodePudding user response:

() to group A-Z mayus chars

  • inside () to group all chars together \n or $ to mach ENTER or End of string

/ "g" to match all and "m" multiline

/([A-Z] )(\n|$)/gm 

CodePudding user response:

/([A-Z]) \n?/g
  • "()" with A-Z to capture the letter group (caps)
  • " " to match at least one letter
  • "\n" to match a line break
  • "?" to match 0 or 1 line break
  • "g" to match all
  • Related