[1-9]?\\d
表示0-99
1\\d{2}
表示100-199
2[0-4]\\d
表示200-249
25[0-5]
表示250-255
|符号分开的表达式只要一个满足就不看后面的表达式了,你的问题就是\\d|[1-9]\\d|1\\d{2}这里就是第一个\\d就满足了。
改成这样
(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]?\\d))
{3}
正则表达式匹配ip地址,实际上就是分别判断每个点直接的数字是否符合规范。\x0d\x0apackage com\x0d\x0a import java.util.regex.Matcher\x0d\x0a import java.util.regex.Pattern\x0d\x0a public class TestRegex { \x0d\x0apublic static boolean isboolIP(String ipAddress){ \x0d\x0a String ip="(2[5][0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})\\.(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})\\.(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})\\.(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})"\x0d\x0aPattern pattern = Pattern.compile(ip)\x0d\x0a Matcher matcher = pattern.matcher(ipAddress) \x0d\x0a return matcher.matches()\x0d\x0a } \x0d\x0a /** * @param args \x0d\x0a */ \x0d\x0a public static void main(String[] args) { \x0d\x0a // TODO Auto-generated method stub \x0d\x0a String ipAddress1 = "10." \x0d\x0a String ipAddress2 = "0.0.0.0"\x0d\x0a String ipAddress3 = "255.255.255.255"\x0d\x0aString ipAddress4 = "192.168.2.1"\x0d\x0a String ipAddress5 = "26445687"\x0d\x0a String ipAddress6 = "nihao"\x0d\x0aString ipAddress7 = "你好!!" \x0d\x0a if(isboolIP(ipAddress1)){ \x0d\x0a System.out.println("IP正确")\x0d\x0a }else{ \x0d\x0a System.out.println("IP错误")\x0d\x0a } if(isboolIP(ipAddress2)){ \x0d\x0aSystem.out.println("IP正确") }else{ \x0d\x0a System.out.println("IP错误") \x0d\x0a } if(isboolIP(ipAddress3)){ \x0d\x0a System.out.println("IP正确") }else{ \x0d\x0a System.out.println("IP错误") \x0d\x0a} \x0d\x0a if(isboolIP(ipAddress4)){ \x0d\x0a System.out.println("IP正确") }else{ \x0d\x0aSystem.out.println("IP错误")你直接用matchs判断就可以了,matcher是只要内部有能匹配上的就算满足,不是判断整体。
String rexp = "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}"String addr = "11111.1.1.1"
System.out.println("1.1.1.1".matches(rexp))
System.out.println("11.1.1.1".matches(rexp))
System.out.println("111.1.1.1".matches(rexp))
System.out.println("11111.1.1.1".matches(rexp))
true
true
true
false