How to Effectively Split a Java String by New Line
Seeking to divide text into distinct lines using a new line character as a separator is a common task when working with strings in Java. Unfortunately, using a single "n" (n) as a regex pattern may not always yield the desired result, particularly when dealing with text originating from different operating systems.
To address this challenge, it's crucial to consider the two main types of newlines: the UNIX new line (n) and the Windows new line (rn). To accommodate both possibilities, a more comprehensive regex expression is required.
The following code snippet exemplifies an effective approach:
String lines[] = string.split("\r?\n");
By utilizing the "?" quantifier, this regex ensures that either zero or one occurrence of the carriage return character (r) precedes the newline character (n). As a result, it successfully handles both UNIX and Windows newline styles, ensuring accurate splitting of the input string into individual lines.
The above is the detailed content of How to Split a Java String by Newline Character Effectively?. For more information, please follow other related articles on the PHP Chinese website!