Java examples for java.util.regex:Match IP Address
parse Ipv4 Address by regex
//package com.java2s; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String[] argv) throws Exception { String address = "java2s.com"; System.out.println(java.util.Arrays .toString(parseIpv4Address(address))); }/*from w ww . j a va 2s .c o m*/ public static final Pattern IPV4_PATTERN = Pattern .compile("(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})"); public static int[] parseIpv4Address(String address) { Matcher m = IPV4_PATTERN.matcher(address); if (!m.find()) { throw new RuntimeException("Invalid IP address: " + address); } int[] octets = new int[4]; octets[0] = Integer.parseInt(m.group(1)); octets[1] = Integer.parseInt(m.group(2)); octets[2] = Integer.parseInt(m.group(3)); octets[3] = Integer.parseInt(m.group(4)); return octets; } }