From b41a78fb3955d4984a6c22681c21cacbd54260f2 Mon Sep 17 00:00:00 2001 From: Mo Helmy <135069400+BenHelmyBen@users.noreply.github.com> Date: Mon, 8 Jan 2024 05:01:27 +0200 Subject: [PATCH] This commit is related to BAEL-7024 (#15564) This commit aims to add a new test class "ReplaceNonPrintableCharsUnitTest". --- .../ReplaceNonPrintableCharsUnitTest.java | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/replacenonprintablecharacters/ReplaceNonPrintableCharsUnitTest.java diff --git a/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/replacenonprintablecharacters/ReplaceNonPrintableCharsUnitTest.java b/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/replacenonprintablecharacters/ReplaceNonPrintableCharsUnitTest.java new file mode 100644 index 0000000000..47a373cd70 --- /dev/null +++ b/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/replacenonprintablecharacters/ReplaceNonPrintableCharsUnitTest.java @@ -0,0 +1,39 @@ +package com.baeldung.replacenonprintablecharacters; + +import org.junit.jupiter.api.Test; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class ReplaceNonPrintableCharsUnitTest { + @Test + public void givenTextWithNonPrintableChars_whenUsingRegularExpression_thenGetSanitizedText() { + String originalText = "\n\nWelcome \n\n\n\tto Baeldung!\n\t"; + String expected = "Welcome to Baeldung!"; + String regex = "[\\p{C}]"; + + Pattern pattern = Pattern.compile(regex); + Matcher matcher = pattern.matcher(originalText); + String sanitizedText = matcher.replaceAll(""); + + assertEquals(expected, sanitizedText); + } + + @Test + public void givenTextWithNonPrintableChars_whenCustomImplementation_thenGetSanitizedText() { + String originalText = "\n\nWelcome \n\n\n\tto Baeldung!\n\t"; + String expected = "Welcome to Baeldung!"; + + StringBuilder strBuilder = new StringBuilder(); + originalText.codePoints().forEach((i) -> { + if (i >= 32 && i != 127) { + strBuilder.append(Character.toChars(i)); + } + }); + + assertEquals(expected, strBuilder.toString()); + } + +}