brewphone
brewphone

Reputation: 1366

Java Regex, remove leading spaces of each line

Want to use Java String.replaceAll(regex, "") to remove all leading spaces of each line in a multi-line text string. if possible remove all carriage-returns as well. What the "regex" should be?

Upvotes: 1

Views: 919

Answers (1)

anubhava
anubhava

Reputation: 784968

Converting my comment to answer so that solution is easy to find for future visitors.

You may use regex replacement in Java:

str = str.replaceAll("(?m)^\\s+|\\s+$", "");

RegEx Details:

  • (?m): Enable MULTILINE mode so that ^ and $ are matched in every line.
  • ^\\s+: Match 1+ whitespaces at line start
  • |: OR
  • \\s+$: Match 1+ whitespaces before line end

Upvotes: 4

Related Questions