正则 匹配IP地址 java
时间: 2023-10-19 08:06:36 浏览: 96
可以使用正则表达式来匹配IP地址,以下是一个Java示例代码:
```java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class IPAddressMatcher {
public static boolean isIPAddress(String input) {
String regex = "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
return matcher.matches();
}
public static void main(String[] args) {
String[] testCases = {"192.168.0.1", "10.0.0.1", "172.16.0.1", "255.255.255.255", "256.256.256.256", "192.168.0"};
for (String input : testCases) {
System.out.println(input + " is IP address? " + isIPAddress(input));
}
}
}
```
上述代码中,使用了正则表达式的字符串 `^([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])$` 来匹配IP地址,其中 `^` 和 `$` 表示限制字符串必须从开头到结尾完全匹配。这个正则表达式的具体含义是:
- `( … )` 表示一个分组。
- `[01]?` 表示 0 或 1 出现 0 次或 1 次。
- `\d` 表示数字。
- `\d\d?` 表示 1 或 2 位数字。
- `2[0-4]\d` 表示 200~249 中的任意一位数字。
- `25[0-5]` 表示 250~255 中的任意一位数字。
- `\.` 表示一个点号,需要使用反斜杠转义。
- `|` 表示或者。
当输入字符串符合 IP 地址的格式时,`matcher.matches()` 返回 `true`,否则返回 `false`。
阅读全文
相关推荐
















