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

Replace all whitespace at all beginning line and empty lines

I have a string like:

   -------beginning certificate


           2323jjjdcnnjjjsd


        sdsdsdsdsdsdsd

and I would like to transform it in (white spaces should be removed only at beginning of each lines):

-------beginning certificate
2323jjjdcnnjjjsd
sdsdsdsdsdsdsd

I have tried with :

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

string.replaceAll("^[\n\r\s]*","");

but seems nothing happens.

>Solution :

You can use:

string = string.replaceAll("(?m)^\\h+|\\h+$|^\\R+", "");

RegEx Demo

Breakdown:

  • (?m): Enable multiline mode
  • ^\\h+: Match 1+ whitespaces at start
  • |: ROR
  • \\h+$: Match 1+ whitespaces before end
  • |: OR
  • ^\\R+: Match 1+ line breaks at start
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