From a4158fd1edbd9e3f9119fc7019dfb23bcc481b05 Mon Sep 17 00:00:00 2001 From: mdhtr Date: Sun, 27 Jun 2021 03:10:43 +0200 Subject: [PATCH] Add examples (#10961) --- .../regex/lookaround/LookaroundUnitTest.java | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 core-java-modules/core-java-regex-2/src/test/java/com/baeldung/regex/lookaround/LookaroundUnitTest.java diff --git a/core-java-modules/core-java-regex-2/src/test/java/com/baeldung/regex/lookaround/LookaroundUnitTest.java b/core-java-modules/core-java-regex-2/src/test/java/com/baeldung/regex/lookaround/LookaroundUnitTest.java new file mode 100644 index 0000000000..eab3793931 --- /dev/null +++ b/core-java-modules/core-java-regex-2/src/test/java/com/baeldung/regex/lookaround/LookaroundUnitTest.java @@ -0,0 +1,61 @@ +package com.baeldung.regex.lookaround; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.junit.jupiter.api.Test; + +public class LookaroundUnitTest { + + @Test + void givenPositiveLookahead_thenSuccess() { + Pattern pattern = Pattern.compile("import (?=static.+).+"); + + Matcher matcher = pattern.matcher("import static org.junit.jupiter.api.Assertions.assertEquals;"); + assertTrue(matcher.find()); + assertEquals("import static org.junit.jupiter.api.Assertions.assertEquals;", matcher.group()); + + assertFalse(pattern.matcher("import java.util.regex.Matcher;") + .find()); + } + + @Test + void givenNegativeLookahead_thenSuccess() { + Pattern pattern = Pattern.compile("import (?!static.+).+"); + + Matcher matcher = pattern.matcher("import java.util.regex.Matcher;"); + assertTrue(matcher.find()); + assertEquals("import java.util.regex.Matcher;", matcher.group()); + + assertFalse(pattern.matcher("import static org.junit.jupiter.api.Assertions.assertEquals;") + .find()); + } + + @Test + void givenPositiveLookbehind_thenSuccess() { + Pattern pattern = Pattern.compile(".*(?<=jupiter).*assertEquals;"); + + Matcher matcher = pattern.matcher("import static org.junit.jupiter.api.Assertions.assertEquals;"); + assertTrue(matcher.find()); + assertEquals("import static org.junit.jupiter.api.Assertions.assertEquals;", matcher.group()); + + assertFalse(pattern.matcher("import static org.junit.Assert.assertEquals;") + .find()); + } + + @Test + void givenNegativeLookbehind_thenSuccess() { + Pattern pattern = Pattern.compile(".*(?