Skip to content

Commit 20455f2

Browse files
committed
[impr-str-between-strs] extract str between 2 strings
1 parent bb4a527 commit 20455f2

File tree

1 file changed

+30
-4
lines changed

1 file changed

+30
-4
lines changed

core-java-modules/core-java-string-operations/src/test/java/com/baeldung/substring/SubstringUnitTest.java

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@
11
package com.baeldung.substring;
22

3-
import static org.junit.Assert.assertEquals;
3+
import org.apache.commons.lang3.StringUtils;
4+
import org.junit.Test;
45

6+
import java.util.ArrayList;
7+
import java.util.List;
58
import java.util.Scanner;
69
import java.util.regex.Matcher;
710
import java.util.regex.Pattern;
811

9-
import org.apache.commons.lang3.StringUtils;
10-
import org.junit.Assert;
11-
import org.junit.Test;
12+
import static org.junit.Assert.assertEquals;
1213

1314
public class SubstringUnitTest {
1415

@@ -111,4 +112,29 @@ public void givenAString_whenSplitWithRegexAndPatternQuote_thenGetDifferentResul
111112
assertEquals("issue.", after);
112113
}
113114

115+
@Test
116+
public void givenAString_whenExtractWithGreedyRegex_thenIncorrect() {
117+
String input = "a <%One%> b <%Two%> c <%Three%>";
118+
Pattern pattern = Pattern.compile("<%(.*)%>");
119+
Matcher matcher = pattern.matcher(input);
120+
List<String> result = new ArrayList<>();
121+
while (matcher.find()) {
122+
result.add(matcher.group(1));
123+
}
124+
assertEquals(1, result.size());
125+
assertEquals("One%> b <%Two%> c <%Three", result.get(0));
126+
}
127+
128+
@Test
129+
public void givenAString_whenExtractWithNonGreedyRegex_thenCorrect() {
130+
String input = "a <%One%> b <%Two%> c <%Three%>";
131+
List<String> expected = List.of("One", "Two", "Three");
132+
Pattern pattern = Pattern.compile("<%(.*?)%>");
133+
Matcher matcher = pattern.matcher(input);
134+
List<String> result = new ArrayList<>();
135+
while (matcher.find()) {
136+
result.add(matcher.group(1));
137+
}
138+
assertEquals(expected, result);
139+
}
114140
}

0 commit comments

Comments
 (0)