1

I've searched around but have not found anything that works. How do I check if a text contains an IP address? I have tried this but it does not work:

    public boolean ip(String a_text) {
    String ip_filter = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}";
    if (a_text.toLowerCase().contains(ip_filter.toLowerCase())){
        return true;
    }
    return false;
}
André Mathisen
  • 904
  • 2
  • 7
  • 15

3 Answers3

12

You're trying to use a Regular Expression with the contains method. And that method does not receive a regex as argument. It receives a plain String. You should try using Pattern and Matcher.

Here's an example:

public static boolean ip(String text) {
    Pattern p = 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]?)$");
    Matcher m = p.matcher(text);
    return m.find();
}

EDIT: I updated the pattern to a more suitable one, found here.

Rodrigo Sasaki
  • 7,048
  • 4
  • 34
  • 49
1

Yes, use match, and a better regular expression that I have used in the past is:

((0|1[0-9]{0,2}|2[0-9]?|2[0-4][0-9]|25[0-5]|[3-9][0-9]?)\.){3}(0|1[0-9]{0,2}|2[0-9]?|2[0-4][0-9]|25[0-5]|[3-9][0-9]?)

From RegExLib

Mihai Bujanca
  • 4,089
  • 10
  • 43
  • 84
Bryan Hobbs
  • 444
  • 2
  • 4
0

You can do a lot of things with Regex. But Why should you!? You already have good and tested libraries, like Guava

boolean isValid = InetAddresses.isInetAddress("1.2.3.4");

Appache Validator

 isValidInet4Address(String)

And so on (see this post)

Community
  • 1
  • 1
evgenyl
  • 7,837
  • 2
  • 27
  • 32