Skip to content

Commit d4b9bf3

Browse files
Merge pull request #16772 from yabetancourt/remove-digits
BAEL-8024: How to remove numeric values from string
2 parents 1147619 + 41ac101 commit d4b9bf3

File tree

2 files changed

+76
-0
lines changed

2 files changed

+76
-0
lines changed

core-java-modules/core-java-string-algorithms-4/pom.xml

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,16 @@
1212
<version>0.0.1-SNAPSHOT</version>
1313
</parent>
1414

15+
<dependencies>
16+
<dependency>
17+
<groupId>org.apache.commons</groupId>
18+
<artifactId>commons-lang3</artifactId>
19+
<version>${commons-lang.version}</version>
20+
</dependency>
21+
</dependencies>
22+
23+
<properties>
24+
<commons-lang.version>3.14.0</commons-lang.version>
25+
</properties>
26+
1527
</project>
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package com.baeldung.string.removedigits;
2+
3+
import org.apache.commons.lang3.RegExUtils;
4+
import org.junit.jupiter.api.Test;
5+
6+
import java.util.regex.Matcher;
7+
import java.util.regex.Pattern;
8+
import java.util.stream.Collectors;
9+
10+
import static org.junit.jupiter.api.Assertions.assertEquals;
11+
12+
public class RemoveDigitsUnitTest {
13+
14+
static final String INPUT_STRING = "M3a9n2y n8u6m7b5e4r0s1";
15+
static final String EXPECTED_STRING = "Many numbers";
16+
static final String DIGIT_REGEX = "\\d";
17+
18+
@Test
19+
void whenUsingReplaceAll_thenGetExpectedResult() {
20+
String updatedString = INPUT_STRING.replaceAll(DIGIT_REGEX, "");
21+
22+
assertEquals(EXPECTED_STRING, updatedString);
23+
}
24+
25+
@Test
26+
void whenUsingPatternAndMatcher_thenGetExpectedResult() {
27+
Pattern pattern = Pattern.compile(DIGIT_REGEX);
28+
Matcher matcher = pattern.matcher(INPUT_STRING);
29+
String updatedString = matcher.replaceAll("");
30+
31+
assertEquals(EXPECTED_STRING, updatedString);
32+
}
33+
34+
@Test
35+
void whenUsingApacheCommonsLang_thenGetExpectedResult() {
36+
String updatedString = RegExUtils.replacePattern(INPUT_STRING, DIGIT_REGEX, "");
37+
38+
assertEquals(EXPECTED_STRING, updatedString);
39+
}
40+
41+
@Test
42+
void whenUsingForLoop_thenGetExpectedResult() {
43+
StringBuilder sb = new StringBuilder();
44+
for (char ch : INPUT_STRING.toCharArray()) {
45+
if (!Character.isDigit(ch)) {
46+
sb.append(ch);
47+
}
48+
}
49+
50+
assertEquals(EXPECTED_STRING, sb.toString());
51+
}
52+
53+
@Test
54+
void whenUsingCharacterStream_thenGetExpectedResult() {
55+
String updatedString = INPUT_STRING.chars()
56+
.filter(c -> !Character.isDigit(c))
57+
.mapToObj(c -> (char) c)
58+
.map(String::valueOf)
59+
.collect(Collectors.joining());
60+
61+
assertEquals(EXPECTED_STRING, updatedString);
62+
}
63+
64+
}

0 commit comments

Comments
 (0)