Reputation: 94
I am trying to validate this pattern:
1.1.1.1 up to 254.254.254.254, but with no leading zeros. so 001.001.001.001 should not match.
I have
/^([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-4])\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-4])\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-4])\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-4])$/
but this matches the leading zeros. Can anyone recommend how to fix this?
Upvotes: 0
Views: 1476
Reputation: 67
Try This.
([1-9]$|[1-9][0-9]$|[12][0-9][0-9]$)\.([0-9]$|[1-9][0-9]$|[12][0-9][0-9]$)\.([0-9]$|[1-9][0-9]$|[12][0-9][0-9]$)\.([1-9]$|[1-9][0-9]$|[12][0-9][0-9]$)
Upvotes: 0
Reputation: 63471
Each element will be:
[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]
Breakdown of parts:
(1-99) (100-199) (200-249) (250-254)
Oh, and one other thing I should mention... You need to handle the number 0
in the 2nd, 3rd and 4rd places. So just put an extra option for a single 0
digit in those groups. I don't think it's valid to have a zero as the first number in an IP address (although it is valid if it's a mask).
Upvotes: 3
Reputation: 1385
This should work
^(([1-9][0-9]?|1[0-9]{2}|2[0-4][0-9]|25[0-4]))\.(?1)\.(?1)\.(?1)$
Upvotes: 0
Reputation: 10224
For repeating patterns like this, it's handy to use numbered repetition. The following should match what you're after
([1-9]\d{0,3}\.){3}[1-9]\d{0,3}
EDIT: I'm asleep and missed the part to cap at .254. I'll update when I get a chance.
Upvotes: 0