用于匹配 IPv4 和 IPv6 字符串的 Java 正则表达式是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46146/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What are the Java regular expressions for matching IPv4 and IPv6 strings?
提问by Kevin Wong
Looking for a string to pass to String#matches(String) that will match IPv4, and another to match IPv6.
寻找一个字符串传递给 String#matches(String) 匹配 IPv4,另一个匹配 IPv6。
回答by Kevin Wong
public static final String IPV4_REGEX = "\A(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_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";
Got these from some blog. Someone good w/ regexes should be able to come up with a single regex for all IPv6 address types. Actually, I guess you could have a single regex that matches both IPv4 and IPv6.
从一些博客上得到这些。有正则表达式的好人应该能够为所有 IPv6 地址类型想出一个正则表达式。实际上,我猜您可以有一个同时匹配 IPv4 和 IPv6 的正则表达式。
回答by Yuval
Another good option for processing IPs is to use Java's classes Inet4Addressand Inet6Address, which can be useful in a number of ways, one of which is to determine the validity of the IP address.
处理 IP 的另一个不错的选择是使用 Java 的类Inet4Address和Inet6Address,它们在许多方面都很有用,其中之一是确定 IP 地址的有效性。
I know this doesn't answer the question directly, but just thought it's worth mentioning.
我知道这并没有直接回答问题,但只是认为值得一提。
回答by hasseg
Here's a regex to match IPv4 addresses:
这是一个匹配 IPv4 地址的正则表达式:
\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b
You'll need to escape the backslashes when you specify it as a string literal in Java:
当您在 Java 中将其指定为字符串文字时,您需要对反斜杠进行转义:
"\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"
回答by Bodhiswatta Mukherjee
package com.capgemini.basics;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
public class Main {
private static Pattern VALID_IPV4_PATTERN = null;
private static Pattern VALID_IPV6_PATTERN1 = null;
private static Pattern VALID_IPV6_PATTERN2 = null;
private static final String ipv4Pattern = "(([01]?\d\d?|2[0-4]\d|25[0-5])\.){3}([01]?\d\d?|2[0-4]\d|25[0-5])";
private static final String ipv6Pattern1 = "([0-9a-f]{1,4}:){7}([0-9a-f]){1,4}";
private static final String ipv6Pattern2 = "^((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)$";
static {
try {
VALID_IPV4_PATTERN = Pattern.compile(ipv4Pattern, Pattern.CASE_INSENSITIVE);
VALID_IPV6_PATTERN1 = Pattern.compile(ipv6Pattern1, Pattern.CASE_INSENSITIVE);
VALID_IPV6_PATTERN2 = Pattern.compile(ipv6Pattern2, Pattern.CASE_INSENSITIVE);
} catch (PatternSyntaxException e) {
System.out.println("Neither");
}
}
public static List<String> validateAddresses(List<String> ipAddress) {
final List<String> validity= new ArrayList<String>();
int len = ipAddress.size();
for(int i=0; i<len; i++){
Matcher m1 = Main.VALID_IPV4_PATTERN.matcher(ipAddress.get(i));
Matcher m12 = Main.VALID_IPV6_PATTERN1.matcher(ipAddress.get(i));
Matcher m22 = Main.VALID_IPV6_PATTERN2.matcher(ipAddress.get(i));
if (m1.matches()) {
validity.add("IPv4");
}
else if(m12.matches() || m22.matches()){
validity.add("IPv6");
}
else{
validity.add("Neither");
}
}
return validity;
}
public static void main(String[] args)
{
final List<String> IPAddress = new ArrayList<String>();
//Test Case 0
/*IPAddress.add("121.18.19.20");
IPAddress.add("0.12.12.34");
IPAddress.add("121.234.12.12");
IPAddress.add("23.45.12.56");
IPAddress.add("0.1.2.3");*/
//Test Case 1
/*IPAddress.add("2001:0db8:0000:0000:0000:ff00:0042:8329");
IPAddress.add("2001:0db8:0:0:0:ff00:42:8329");
IPAddress.add("::1");
IPAddress.add("2001:0db8::ff00:42:8329");
IPAddress.add("0000:0000:0000:0000:0000:0000:0000:0001");*/
//Test Case 2
/*IPAddress.add("000.012.234.23");
IPAddress.add("666.666.23.23");
IPAddress.add(".213.123.23.32");
IPAddress.add("23.45.22.32.");
IPAddress.add("272:2624:235e:3bc2:c46d:682:5d46:638g");
IPAddress.add("1:22:333:4444");*/
final List<String> result = validateAddresses(IPAddress);
for (int i=0; i<result.size(); i++)
System.out.println(result.get(i)+" ");
}
}
回答by Aeron
The regex allows the use of leading zeros in the IPv4 parts.
正则表达式允许在 IPv4 部分使用前导零。
Some Unix and Mac distros convert those segments into octals.
一些 Unix 和 Mac 发行版将这些段转换为八进制。
I suggest using 25[0-5]|2[0-4]\d|1\d\d|[1-9]?\das an IPv4 segment.
我建议25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d用作 IPv4 段。
回答by Sean F
Regexes for ipv6 can get really tricky when you consider addresses with embedded ipv4 and addresses that are compressed.
当您考虑带有嵌入式 ipv4 的地址和压缩的地址时,ipv6 的正则表达式可能会变得非常棘手。
The open-source IPAddress Java librarywill validate all standard representations of IPv6 and IPv4 and also supports prefix-length (and validation of such). Disclaimer: I am the project manager of that library.
开源 IPAddress Java 库将验证 IPv6 和 IPv4 的所有标准表示,并且还支持前缀长度(以及此类验证)。免责声明:我是那个图书馆的项目经理。
Code example:
代码示例:
try {
IPAddressString str = new IPAddressString("::1");
IPAddress addr = str.toAddress();
} catch(AddressStringException e) {
//e.getMessage has validation error
}

