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.
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.
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;
}
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}")