Hi my regex pattern is
^((?:(?:^|\.)(?:\d|[1-9]\d|1\d{2}|2[-4]\d|25[0-5])){4})$
this allow 0.0.0.0
but i do not want to allow 0.0.0.0
please someone help me
Hi my regex pattern is
^((?:(?:^|\.)(?:\d|[1-9]\d|1\d{2}|2[-4]\d|25[0-5])){4})$
this allow 0.0.0.0
but i do not want to allow 0.0.0.0
please someone help me
Just add a negative lookahead assertion at the start.
^(?!0+\.0+\.0+\.0+$)((?:(?:^|\.)(?:\d|[1-9]\d|1\d{2}|2[-4]\d|25[0-5])){4})$
^(?=.*[1-9])((?:(?:^|\.)(?:\d|[1-9]\d|1\d{2}|2[-4]\d|25[0-5])){4})$
You can do this through positive lookahead.
See demo.
A look-ahead can be used to set a length limit. In this case, it can be quite concise, since the string should only contain digits and .
symbol.
Thus, I suggest using (?![0.]+$)
as we only need to check if we have no 0
s and periods up to the end:
^(
(?![0.]+$) # Here is the look-ahead.
(?:
(?:^|\.)
(?:
\d|[1-9][0-9]|1\d{2}|2[-4]\d|25[0-5]
)
){4}
)$
See demo
^((?![0.]+$)(?:(?:^|\.)(?:\d|[1-9][0-9]|1\d{2}|2[-4]\d|25[0-5])){4})$
Is this part of an assignment?
If not, I would use no regex and prefer String#scan :
ip_subnets = ip.scan(/\d+/).map(&:to_i) # you can use split('.') instead of scan
ip_subnets.all? { |i| (0..255).include?(i) } &&
ip_subnets.any? { |i| i != 0 } &&
ip_subnets.size == 4