From d1bbd3502ba409e1b661a16073ec244805c77399 Mon Sep 17 00:00:00 2001 From: unknown Date: Sat, 20 Feb 2021 21:08:27 +0530 Subject: [PATCH] BAEL-4702 - Code snippets for split Java String by New line --- .../SplitStringByNewLineUnitTest.java | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 core-java-modules/core-java-string-operations-3/src/test/java/com/baeldung/splitstringbynewline/SplitStringByNewLineUnitTest.java diff --git a/core-java-modules/core-java-string-operations-3/src/test/java/com/baeldung/splitstringbynewline/SplitStringByNewLineUnitTest.java b/core-java-modules/core-java-string-operations-3/src/test/java/com/baeldung/splitstringbynewline/SplitStringByNewLineUnitTest.java new file mode 100644 index 0000000000..71b39ce542 --- /dev/null +++ b/core-java-modules/core-java-string-operations-3/src/test/java/com/baeldung/splitstringbynewline/SplitStringByNewLineUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.splitstringbynewline; + +import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; + +public class SplitStringByNewLineUnitTest { + + @Test + public void givenString_whenSplitByNewLineUsingRegularExpressionPattern_thenReturnsArray() { + assertThat("Line1\nLine2\nLine3".split("\\r?\\n|\\r")).containsExactly("Line1", "Line2", "Line3"); + + assertThat("Line1\rLine2\rLine3".split("\\r?\\n|\\r")).containsExactly("Line1", "Line2", "Line3"); + + assertThat("Line1\r\nLine2\r\nLine3".split("\\r?\\n|\\r")).containsExactly("Line1", "Line2", "Line3"); + } + + @Test + public void givenString_whenSplitByNewLineUsingJava8Pattern_thenReturnsArray() { + assertThat("Line1\nLine2\nLine3".split("\\R")).containsExactly("Line1", "Line2", "Line3"); + + assertThat("Line1\rLine2\rLine3".split("\\R")).containsExactly("Line1", "Line2", "Line3"); + + assertThat("Line1\r\nLine2\r\nLine3".split("\\R")).containsExactly("Line1", "Line2", "Line3"); + } + + +}