Skip to content

Instantly share code, notes, and snippets.

@tristantarrant
Created December 2, 2013 15:35
Show Gist options
  • Select an option

  • Save tristantarrant/7751258 to your computer and use it in GitHub Desktop.

Select an option

Save tristantarrant/7751258 to your computer and use it in GitHub Desktop.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class IPvXTest {
static void match(String s) {
Pattern p = Pattern.compile("(\\[(?<v6host>[0-9A-Fa-f:]+)\\]|(?<v4host>[^:/?#]*))(?::(?<port>\\d*))?");
Matcher matcher = p.matcher(s);
if (matcher.matches()) {
String v6host = matcher.group("v6host");
String v4host = matcher.group("v4host");
System.out.printf("Host = %s Port = %s\n", v6host != null ? v6host : v4host, matcher.group("port"));
} else {
System.err.printf("%s doesn't match", s);
}
}
public static void main(String[] args) {
match("[::1]:11222");
match("[ff01::1]:11222");
match("[ff01::1]");
match("127.0.0.1:11222");
match("myhost");
match("myhost:11222");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment