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

Matching spaces between \n to a character in regex to remove whitespaces at the start of a line

I am trying to write a regex expression to remove the spaces between a \n to the next alpha numeric character, however I was not able to succeed,

This would be an example:

IF THIS IS THE CODE
      AND THIS IS THE NEXT LINE
    AND THIS IS THE THIRD LINE

I would like to transform this into:

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

IF THIS IS THE CODE
AND THIS IS THE NEXT LINE
AND THIS IS THE THIRD LIN

I’ve tried enough but I could really use some help right here!

>Solution :

  1. Match a new line with \n
  2. Match all the spaces with \s* (zero or more spaces)
  3. Match the beginning of the nearest word with \b

Your regex becomes: /\n\s+\b/gm

Test here: https://regex101.com/r/fTZDJu/2

Since you dont want \n in the match, you can match the beginning of each line and then replace the spaces till the nearest word.

Change the regex to : /^\s+\b/gm, ‘^’ indicates the beginning of a line. Test: https://regex101.com/r/hpVS6x/1

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