Reputation: 5
I am trying to validate whether a number with decimals in between is within the range of 0-255 which allows leading zeroes.
So far I have come up with the regex
^0*([1-9][\.\d]|250)*
and the example that I have tried it on is 63.32.32.250 however it only grabs the 63, and not the rest of the string.
I thought [\.\d] would include all the periods, however it isn't the case.
What am I doing wrong here? Thanks
Upvotes: 0
Views: 87
Reputation: 34
Federico Piazza's answer is better but if you want to do it manually I would think about using the split function and checking using ><, e.g...
String[] numbers = "63.32.32.250".split("\\.");
for(String number: numbers){
-> parse number string to an int
-> check its in right range just with ><=
}
Hope that helps
Upvotes: 1
Reputation: 9650
For one group of digits:
^0*([0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])$
For four groups, repeat:
^0*([0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.0*([0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.0*([0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.0*([0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])$
This will capture four groups.
Upvotes: 0
Reputation: 18773
To validate IPv4 addresses you would do something like
^((?:\d{1,3}\.){3}\d{1,3})$
But this has the vital flaw of not checking if the number is between 1-255
^(?:(?: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]?)$
Upvotes: 0
Reputation: 30995
Using a regex for this is not a good idea, you can use InetAddressValidator like this:
InetAddressValidator.getInstance().isValid(YOUR_IP_HERE)
Btw, you can use isValidInet4Address
method as well.
Upvotes: 2