Header Ads

Header ADS

java String Split

Split New Line

In *Nix environment, lines are just separated by the character "\n". In Windows however, the separator is "\r\n". To combine the logic for both scenario, the correct regular expression to denote line feeds for both platform is "\r?\n". This means that "\r" is optional while "\n" is required.
*Nix line feed Example
Here is an example code assuming *Nix environment. 
public class TestConsole {
   public static void main(String[] args) {
      String nixSampleLine = "Line 1 \n Line 2 \n Line 3";
      String[] lines = nixSampleLine.split("\\r?\\n");
      for (String line : lines) {
         System.out.println(line);
      }
   }
}
Here is the output: 
Line 1 
 Line 2 
 Line 3

No comments

Theme images by Matt Vince. Powered by Blogger.