简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM