1

I need to find if a string (in Java) contains IPv4 address (it can be present anywhere). I used the following line but it fails :

if (token.matches(".[0-9]{1,3}/..[0-9]{1,3}/..[0-9]{1,3}/..[0-9]{1,3}") == true) 

what can be wrong here.

j10
  • 2,009
  • 3
  • 27
  • 44
  • You can get some [help](http://answers.oreilly.com/topic/318-how-to-match-ipv4-addresses-with-regular-expressions/) here . – AllTooSir Jun 05 '13 at 17:09
  • 2
    you don't need to say == true either, that's redundant – sjr Jun 05 '13 at 17:10
  • 2
    see: http://stackoverflow.com/questions/5284147/validating-ipv4-addresses-with-regexp – DannyMo Jun 05 '13 at 17:11
  • What do you mean by "present anywhere"? – fge Jun 05 '13 at 17:15
  • @fge the IP address could be anywhere in the string . As in not at the begginning or end. – j10 Jun 05 '13 at 17:20
  • @damo I tried this token.matches("\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\\.|$)){4}\b") but does not work. – j10 Jun 05 '13 at 17:20
  • I found one pattern "(([0-9](?!\\d)|[1-9][0-9](?!\\d)|1[0-9]{2}(?!\\d)|2[0-4][0-9](?!\\d)|25[0-5](?!\\d))[.]?){4}" but how can I make sure this pattern can occur anywhere in the string ? – j10 Jun 05 '13 at 17:39
  • I got it . I added ".*" at the end and beginning of the above pattern and it works now. thanks – j10 Jun 05 '13 at 17:45

2 Answers2

1

Using a pure regex for that is possible, but there are tools to check the validity of an IP address already.

Supposing the string is a list of tokens separated by spaces you can do that:

// Crude check
private static final Pattern PATTERN = Pattern.compile("\\d+(\.\\d+){3}");

public boolean containsIPAddress(final String input) 
{
    for (final String candidate: input.split("\\s+")) {
        if (!PATTERN.matcher(candidate).matches())
            continue;
        try {
            InetAddress.getByName(candidate);
            return true;
        } catch (UnknownHostException ignored) {
        }
    }

    return false;
}

Using Guava, it is even easier:

private static final Splitter SPLITTER = Splitter.on(' ');

public boolean containsIPAddress(final String input) 
{
    for (final String candidate: SPLITTER.split(input)) {
        if (InetAddresses.isInetAddress(candidate))
            return true;

    return false;
}
fge
  • 119,121
  • 33
  • 254
  • 329
  • thanks fge but the problem is the IP address may be attach with a prefix like say /23 or /32 . So I need a pattern which can match anywhere in the String – j10 Jun 05 '13 at 17:39
0

The direction of slash is wrong. This is not the file system path where you can safely use forward slash instead of backslash. This is regular expression, so you have to use real back slash \ and duplicate it because you are writing java code: \\

So, here is the expression:

token.matches("(?:\\d\\.){1,3}\\d{1,3}")

AlexR
  • 114,158
  • 16
  • 130
  • 208