Home > Back-end >  Extracting Ip address from a string with predefined template using regex Java
Extracting Ip address from a string with predefined template using regex Java

Time:12-03

I want to extract the IP address from the input string

[IP-Address]: [ipv4]: [10.124.25.210]

using Pattern matching in Java. There are 2 whitespaces after :.

What would be the regex for the same?

The pattern that I tried with was:

Pattern p2 = Pattern.compile("\\[.*\\]\\:  \\[.*\\]\\:  \\[(.*?)\\]");

But obviously it didn't work, as I am new to regex.

CodePudding user response:

Assuming your input be precisely what you specified in your question, you could just use a regex replacement here:

String input = "[IP-Address]: [ipv4]: [10.124.25.210]";
String ip = input.replaceAll(".*\\[|\\]", "");
System.out.println(ip);  // 10.124.25.210

You could also be more specific in your regex:

String input = "[IP-Address]: [ipv4]: [10.124.25.210]";
String ip = input.replaceAll(".*\\[(\\d (?:\\.\\d ){3})\\].*", "$1");
System.out.println(ip);  // 10.124.25.210

CodePudding user response:

To extract the IP address from the input string, you can use the following regex:

\[IP-Address\]\: \s\[ipv4\]\: \s\[(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\]

This regex will match the input string and capture the IP address in a capture group. Here is how you can use this regex in a Java Pattern object:

// Compile the regex pattern
Pattern p2 = Pattern.compile("\\[IP-Address\\]: \\s\\[ipv4\\]: \\s\\[(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})\\]");

// Create a Matcher object for the input string
Matcher m2 = p2.matcher("[IP-Address]: [ipv4]: [10.124.25.210]");

// Check if the input string matches the regex pattern
if (m2.matches()) {
    // Print the captured IP address
    System.out.println("IP address: "   m2.group(1));
}

This code should print the following output:

IP address: 10.124.25.210

CodePudding user response:

For your requirement the regex, (?:\d{1,3}\.){3}\d{1,3} is enough.

  • (?: - start of the non-capturing group
    • \d{1,3}\. - one to three digits followed by a dot
  • ) - end of the non-capturing group
  • {3} - three times (the things matched with the non-capturing group)
  • \d{1,3} - one to three digits

Demo:

public class Main {
    public static void main(String[] args) {
        String text = "[IP-Address]: [ipv4]: [10.124.25.210]";
        Matcher matcher = Pattern.compile("(?:\\d{1,3}\\.){3}\\d{1,3}").matcher(text);
        if (matcher.find())
            System.out.println(matcher.group());
    }
}

Output:

10.124.25.210
  • Related