1
1
package com .baeldung .string ;
2
2
3
-
4
3
import org .apache .commons .lang3 .StringUtils ;
4
+ import org .apache .commons .lang3 .RegExUtils ;
5
5
import org .junit .Test ;
6
6
7
7
import static org .junit .Assert .assertFalse ;
8
8
import static org .junit .Assert .assertTrue ;
9
9
10
10
public class StringReplaceAndRemoveUnitTest {
11
11
12
-
13
12
@ Test
14
13
public void givenTestStrings_whenReplace_thenProcessedString () {
15
14
@@ -26,7 +25,7 @@ public void givenTestStrings_whenReplace_thenProcessedString() {
26
25
public void givenTestStrings_whenReplaceAll_thenProcessedString () {
27
26
28
27
String master2 = "Welcome to Baeldung, Hello World Baeldung" ;
29
- String regexTarget = "(Baeldung)$" ;
28
+ String regexTarget = "(Baeldung)$" ;
30
29
String replacement = "Java" ;
31
30
String processed2 = master2 .replaceAll (regexTarget , replacement );
32
31
assertTrue (processed2 .endsWith ("Java" ));
@@ -45,18 +44,16 @@ public void givenTestStrings_whenStringBuilderMethods_thenProcessedString() {
45
44
46
45
StringBuilder builder = new StringBuilder (master );
47
46
48
-
49
47
builder .delete (startIndex , stopIndex );
50
- assertFalse (builder .toString (). contains ( target ));
51
-
48
+ assertFalse (builder .toString ()
49
+ . contains ( target ));
52
50
53
51
builder .replace (startIndex , stopIndex , replacement );
54
- assertTrue (builder .toString (). contains ( replacement ));
55
-
52
+ assertTrue (builder .toString ()
53
+ . contains ( replacement ));
56
54
57
55
}
58
56
59
-
60
57
@ Test
61
58
public void givenTestStrings_whenStringUtilsMethods_thenProcessedStrings () {
62
59
@@ -74,10 +71,20 @@ public void givenTestStrings_whenStringUtilsMethods_thenProcessedStrings() {
74
71
75
72
}
76
73
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
+ }
77
81
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
+ }
82
89
83
90
}
0 commit comments