Home > Software design >  Replace all whitespace at all beginning line and empty lines
Replace all whitespace at all beginning line and empty lines

Time:10-22

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 :

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

but seems nothing happens.

CodePudding user response:

You can use:

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

RegEx Demo

Breakdown:

  • (?m): Enable multiline mode
  • ^\\s : Match 1 whitespaces (including line breaks) at start
  • |: OR
  • \\h $: Match 1 horizontal whitespaces before end

CodePudding user response:

Reasons why it's not working could be that:

  1. Backslash was not escaped
  2. Lack of multiline flag, so ^ only matches start of the string and not start of each line.

Further to mention that \s already contains \r and \n. You should be fine using (as a Java String)

"^\\s "

See this demo at regex101 or Java demo at tio.run (compile with MULTILINE or use (?m) flag)
Note that I also changed the * quantifier to for matching one or more whitespaces.

CodePudding user response:

I hope that will be useful. this code removes white spaces from beginning of lines and blank lines from a string

string.replaceAll("(?m)^[\\s&&[^\\n]] ", "").replace("(?m)^[\n]","")

This is the shorter form.

string.replaceAll("(?m)^[\\s&&[^\\n]] |^[\n]", "")
  • Related