Skip to content

Commit f6240fd

Browse files
authored
[extract-ip] extract ip (#17917)
1 parent 7a1a897 commit f6240fd

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package com.baeldung.extractip;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
5+
import java.util.ArrayList;
6+
import java.util.Collections;
7+
import java.util.List;
8+
import java.util.regex.Matcher;
9+
import java.util.regex.Pattern;
10+
11+
import org.junit.jupiter.api.Test;
12+
13+
public class ExtractIpAddressUnitTest {
14+
15+
private static final String INPUT1 = "No IP address here";
16+
private static final List<String> EXPECTED1 = Collections.emptyList();
17+
18+
private static final String INPUT2 = "My local ip is 127.0.0.1";
19+
private static final List<String> EXPECTED2 = List.of("127.0.0.1");
20+
21+
private static final String INPUT3 = "Another ip address is 192.168.42.42";
22+
private static final List<String> EXPECTED3 = List.of("192.168.42.42");
23+
24+
private static final String INPUT4 = "Extract the valid part: 260.1.2.345";
25+
private static final List<String> EXPECTED4 = List.of("60.1.2.34");
26+
27+
private static final String INPUT5 = "No valid ip address 260.42.342.345";
28+
private static final List<String> EXPECTED5 = Collections.emptyList();
29+
30+
private static final String INPUT6 = "We have multiple ip addresses: 127.1.1.0, 192.168.42.42 and 245.30.1.34";
31+
private static final List<String> EXPECTED6 = List.of("127.1.1.0", "192.168.42.42", "245.30.1.34");
32+
33+
private static final Pattern IP_PATTERN = Pattern.compile("(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)[.]){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)");
34+
35+
List<String> extractIP(String input) {
36+
Matcher matcher = IP_PATTERN.matcher(input);
37+
List<String> result = new ArrayList<>();
38+
while (matcher.find()) {
39+
result.add(matcher.group());
40+
}
41+
return result;
42+
}
43+
44+
@Test
45+
void whenExtractIpAddress_thenCorrect() {
46+
assertEquals(EXPECTED1, extractIP(INPUT1));
47+
assertEquals(EXPECTED2, extractIP(INPUT2));
48+
assertEquals(EXPECTED3, extractIP(INPUT3));
49+
assertEquals(EXPECTED4, extractIP(INPUT4));
50+
assertEquals(EXPECTED5, extractIP(INPUT5));
51+
assertEquals(EXPECTED6, extractIP(INPUT6));
52+
}
53+
}

0 commit comments

Comments
 (0)