11package 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 ;
58import java .util .Scanner ;
69import java .util .regex .Matcher ;
710import 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
1314public 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