11package com .baeldung .string ;
22
3-
43import org .apache .commons .lang3 .StringUtils ;
4+ import org .apache .commons .lang3 .RegExUtils ;
55import org .junit .Test ;
66
77import static org .junit .Assert .assertFalse ;
88import static org .junit .Assert .assertTrue ;
99
1010public class StringReplaceAndRemoveUnitTest {
1111
12-
1312 @ Test
1413 public void givenTestStrings_whenReplace_thenProcessedString () {
1514
@@ -26,7 +25,7 @@ public void givenTestStrings_whenReplace_thenProcessedString() {
2625 public void givenTestStrings_whenReplaceAll_thenProcessedString () {
2726
2827 String master2 = "Welcome to Baeldung, Hello World Baeldung" ;
29- String regexTarget = "(Baeldung)$" ;
28+ String regexTarget = "(Baeldung)$" ;
3029 String replacement = "Java" ;
3130 String processed2 = master2 .replaceAll (regexTarget , replacement );
3231 assertTrue (processed2 .endsWith ("Java" ));
@@ -45,18 +44,16 @@ public void givenTestStrings_whenStringBuilderMethods_thenProcessedString() {
4544
4645 StringBuilder builder = new StringBuilder (master );
4746
48-
4947 builder .delete (startIndex , stopIndex );
50- assertFalse (builder .toString (). contains ( target ));
51-
48+ assertFalse (builder .toString ()
49+ . contains ( target ));
5250
5351 builder .replace (startIndex , stopIndex , replacement );
54- assertTrue (builder .toString (). contains ( replacement ));
55-
52+ assertTrue (builder .toString ()
53+ . contains ( replacement ));
5654
5755 }
5856
59-
6057 @ Test
6158 public void givenTestStrings_whenStringUtilsMethods_thenProcessedStrings () {
6259
@@ -74,10 +71,20 @@ public void givenTestStrings_whenStringUtilsMethods_thenProcessedStrings() {
7471
7572 }
7673
74+ @ Test
75+ public void givenTestStrings_whenReplaceExactWord_thenProcessedString () {
76+ String sentence = "A car is not the same as a carriage, and some planes can carry cars inside them!" ;
77+ String regexTarget = "\\ bcar\\ b" ;
78+ String exactWordReplaced = sentence .replaceAll (regexTarget , "truck" );
79+ assertTrue ("A truck is not the same as a carriage, and some planes can carry cars inside them!" .equals (exactWordReplaced ));
80+ }
7781
78-
79-
80-
81-
82+ @ Test
83+ public void givenTestStrings_whenReplaceExactWordUsingRegExUtilsMethod_thenProcessedString () {
84+ String sentence = "A car is not the same as a carriage, and some planes can carry cars inside them!" ;
85+ String regexTarget = "\\ bcar\\ b" ;
86+ String exactWordReplaced = RegExUtils .replaceAll (sentence , regexTarget , "truck" );
87+ assertTrue ("A truck is not the same as a carriage, and some planes can carry cars inside them!" .equals (exactWordReplaced ));
88+ }
8289
8390}
0 commit comments