Home >Java >javaTutorial >How to Split a Java String by Newline Character Effectively?

How to Split a Java String by Newline Character Effectively?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-03 17:22:40811browse

How to Split a Java String by Newline Character Effectively?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn