Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

1. Overview

When processing log files or analyzing network traffic data, we often need to extract IP addresses from a given String in Java.

In this tutorial, we’ll examine the format of IPv4 addresses and then create a solution using Java’s regular expression (regex) capabilities.

2. A Few Words About IP Addresses

An IPv4 address consists of four octets separated by dots, where each octet is a number between 0 and 255. This means that a valid IPv4 address looks like:

0.0.0.0
192.168.0.8
234.223.43.42
255.255.255.0

Next, we’ll craft a regex pattern to identify any sequence of characters in the form of an IP address. Then, we can extract all IP addresses from a String by applying this pattern.

3. Creating the Regex Matching an IP Address

Let’s first look at the regex and then understand why it matches an IP address:

(?:(?: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]?)

We used non-capturing groups (?: ) in this regex. Non-capturing groups group things without creating a backreference.

Let’s look at the octet pattern later to understand the regex structure more easily. Then, the regex looks like:

(?:(?:OCTET_PATTERN)[.]){3}(?:OCTET_PATTERN)

This part matches the first three ({3}) octets, followed by a literal dot and the fourth octet at the end. It’s worth mentioning that although “.” means any single character in regex if we put it in the character class “[.]“, it matches a literal dot character.

Next, let’s take a closer look at the OCTET_PATTERN:

(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)

This part matches any valid number between 0 and 255 by combining three possibilities. Let’s look at each option within this inner group.

  • 25[0-5] – Matches numbers from 250 to 255
  • 2[0-4][0-9] – Matches numbers from 200 to 249
  • [01]?[0-9][0-9]? – Matches numbers from 0 to 199.

Now that we understand the regex let’s create a Java method to extract IP addresses from a String.

4. Creating a Method to Extract IP Addresses

First, let’s obtain a Pattern instance from the regex we’ve discussed:

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]?)");

Since a String can contain multiple IP addresses, let’s create a method that accepts an input and returns a List of String values as extracted IP addresses:

List<String> extractIP(String input) {
    Matcher matcher = IP_PATTERN.matcher(input);
    List<String> result = new ArrayList<>();
    while (matcher.find()) {
        result.add(matcher.group());
    }
    return result;
}

The method is pretty straightforward. Using matcher.find(), we iterate over the String, collecting each match into a pre-initialized ArrayList. Every time find() gets called, matcher.group() returns the matching substring (an IP address), which we add to the result List.

Next, let’s create some test data to verify if our method works as expected:

First, if a String doesn’t contain any IP address, we expect to get an empty list:

static final String INPUT1 = "No IP address here";
static final List<String> EXPECTED1 = Collections.emptyList();

When a String contains a single IP address, the result List should contain the expected IP address:

static final String INPUT2 = "My local ip is 127.0.0.1";
static final List<String> EXPECTED2 = List.of("127.0.0.1");
 
static final String INPUT3 = "Another ip address is 192.168.42.42";
static final List<String> EXPECTED3 = List.of("192.168.42.42");

As mentioned, each octet should be between 0 and 255, so we should only extract the valid part:

static final String INPUT4 = "Extract the valid part: 260.1.2.345";
static final List<String> EXPECTED4 = List.of("60.1.2.34");

If there is no valid IP address in the input, the result should be empty:

static final String INPUT5 = "No valid ip address 260.42.342.345";
static final List<String> EXPECTED5 = Collections.emptyList();

Of course, if the input contains multiple IP addresses, we should get all of them:

static final String INPUT6 = "We have multiple ip addresses: 127.1.1.0, 192.168.42.42 and 245.30.1.34";
static final List<String> EXPECTED6 = List.of("127.1.1.0", "192.168.42.42", "245.30.1.34");

Finally, let’s test our method using these inputs:

assertEquals(EXPECTED1, extractIP(INPUT1));
assertEquals(EXPECTED2, extractIP(INPUT2));
assertEquals(EXPECTED3, extractIP(INPUT3));
assertEquals(EXPECTED4, extractIP(INPUT4));
assertEquals(EXPECTED5, extractIP(INPUT5));
assertEquals(EXPECTED6, extractIP(INPUT6));

When we run the test, it passes. Therefore, the method solves the problem.

5. Conclusion

In this article, we’ve learned how to extract IP addresses from a String in Java. Using regular expressions, we created a pattern that detects valid IPv4 addresses. Then, based on the regex pattern, we implemented a solution to capture each IP in a given string.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

3 Comments
Oldest
Newest