1

可能重复:
匹配 IPv4 和 IPv6 字符串的 Java 正则表达式是什么?

有没有人有一个java代码来解压给定的IPv6地址。

我发现编写正则表达式真的很困难。

4

2 回答 2

3

其中之一应该可以帮助您:

public static final String IPV6_HEX4DECCOMPRESSED_REGEX = "\\A((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?) ::((?:[0-9A-Fa-f]{1,4}:)*)(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z";
public static final String IPV6_6HEX4DEC_REGEX = "\\A((?:[0-9A-Fa-f]{1,4}:){6,6})(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z";
public static final String IPV6_HEXCOMPRESSED_REGEX = "\\A((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)\\z";
public static final String IPV6_REGEX = "\\A(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\\z";

还可以查看Inet6Address 类,这将使您的生活更轻松。

参考:

于 2012-08-15T19:36:44.440 回答
0

为什么在可以使用时使用正则表达式Inet6Address.getHostAddress

final String compressed = "1080::8:800:200c:417a";
final String decompressed = "1080:0:0:0:8:800:200c:417a";
try {
  final Inet6Address addr = (Inet6Address) InetAddress.getByName(compressed);
  assert addr.getHostAddress().equals(decompressed);
} catch (UnknownHostException ex) { }
于 2012-08-15T19:39:14.833 回答