Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to Join Two Last Non-Empty Lines Before a Specific Pattern?

I have a list like following:

1.58%
0009
1991
/////////////////////////
Phil
ttr0018
1991
/////////////////////////

Now I want to join two last non-empty lines before ///////////////////////// lines like following (what output I want):

1.58%
0009 1991
/////////////////////////
Phil
ttr0018 1991
/////////////////////////

I tried following regex but not working:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Find : ^(\h*\S.*)(?=\R+(?:\h*\S.*\R+)?/{24})
Replace : \1

Where is problem?

>Solution :

Currently you are using a single match with a capture group in your regex, where the replacement with group 1 will give back the same result.

What yo might do is use 2 capture groups, and replace with $1 $2

^(\h*\S.*)(?:\R\h*)*\R(\h*\S.*)(?:\R\h*)*(?=\R/{24})

See a regex demo

Or a bit shorter, using $1 $2\n in the replacement.

^(\h*\S.*)\R\s*^(\h*\S.*)\R\s*^(?=/{24})

The pattern matches:

  • (\h*\S.*) Capture group 1, match optional leading horizontal whitespace chars, at least a non whitespace char and the rest of the line
  • \R\s*^ Match a newline, optional whitespace chars and assert the start of the string
  • (\h*\S.*) Capture group 2, same pattern as group 1
  • \R\s*^ Same as previous pattern
  • (?=/{24}) Positive lookahead, assert 24 times a / char

See another regex demo

enter image description here


As a side note, using ^(\h*\S.*) can by itself also match only forward slashes.

If you want to prevent that, you could use for example a negative lookahead to assert not 24 times a forward slash

^(?!/{24})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading