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

Time:02-16

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:

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!

CodePudding user response:

  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

  • Related