Search code examples
javastringremoving-whitespace

How can Java remove leading whitespace?


I have been trying to figure out why this Java code won't delete any leading whitespace to my actual string, I have been trying to use stripLeading() method and the trim(); method, and various other methods with the same functionality but still haven't gotten a favorable outcome. Code:

public static String message(String logLine) {
         logLine = (String) logLine.subSequence(logLine.indexOf(" ") + 1, logLine.length());
         return logLine;
         }
public static void main(String[] args) {
        
        System.out.println(message("[WARNING]:   \tTimezone not set  \r\n"));
    }

What results is what I wanted, just the words "Timezone not set" however I want this program to completely ignore leading whitespace, which for some reason it can't. Thank you for any help.


Solution

  • Possible solutions

    • Use String::replaceFirst to keep only the part after a prefix ([WARNING]:) followed by whitespaces and the main part:

      public static String message(String logLine) {
          return logLine.replaceFirst("^\\S*\\s+(\\S+(\\s+\\S+)*)\\s+$", "$1");
      }
      
    • As the prefix ends with ':', a solution offered in the comment using String::substring + String::trim works too:

      public static String message(String logLine) {
          return logLine.substring(logLine.indexOf(":") + 1).trim();
      }