I am trying to write a regex for validating an IP address.
While this works:
String reg = "((0|1)?\\d{1,2}|2[0-4]\\d|25[0-5])";
public String pattern = reg + "." + reg + "." + reg + "." + reg;
This doesn't seem to work and I don't understand what is wrong.
String pattern = "((0|1)?\\d{1,2}|2[0-4]\\d|25[0-5]\\.){3}((0|1)?\\d{1,2}|2[0-4]\\d|25[0-5])";
Please explain what am I missing.
You are not grouping correctly: the dot \\. is part of the 25[0-5] production, so it wouldn't be matched in the middle of your three-part group unless the address consists exclusively of 25x components.
Your first regex is free from this problem because dots are added outside the grouping parentheses. However, the dots are not escaped, meaning that the expression would match some incorrect strings along with the correct ones (e.g. 123a210b132c210)
Adding parentheses around your digit productions fixes this problem:
(((0|1)?\d{1,2}|2[0-4]\d|25[0-5])\.){3}((0|1)?\d{1,2}|2[0-4]\d|25[0-5])
//^ ^
Demo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With