Reputation: 435
With a lot of trying I have managed to create the following regex. I want to use this to prevent the spamming of IP's.
([0-9]{1,3}(\.+|\s+)){3}[0-9]{1,3}
This will catch all the ips if written correctly
for example 8.8.8.8
However it doesn't match "8. 8. 8. 8"
or "8 .8 .8 .8"
\s*
But I don't seem to get it working, could anyone help me, and explain me where I need to place the \s*
to ignore Spaces in between
Regards Jurre
Upvotes: 3
Views: 6627
Reputation: 120496
^\s*(?:(?:[2](?:[5][0-5]|[0-4][0-9])|[01]?[0-9][0-9]?)\s*(?:\.\s*(?=[0-9])|(?![0-9]))){4}$
should do it.
To break this down,
(?:[2](?:[5][0-5]|[0-4][0-9])|[01]?[0-9][0-9]?)
matches any non-negative decimal integer of at most three digits in the range [0,255].\s*
matches zero or more spaces.(?:\.\s*(?=[0-9])|(?![0-9]))
matches a dot and space when followed by more digits or the end of the digits{4}
requires four repetitions of this wholeTo make it more readable, you can break it down:
String INT_IN_0_TO_255 = "(?:[2](?:[5][0-5]|[0-4][0-9])|[01]?[0-9][0-9]?)";
String OPTIONAL_SPACE = "\\s*";
String DOT_BEFORE_MORE_NUMBERS = "(?:\.\s*(?=[0-9])|(?![0-9]))";
String NUMERIC_IP_ADDRESS =
"^"
+ OPTIONAL_SPACE
+ "(?:"
+ INT_IN_0_TO_255
+ OPTIONAL_SPACE
+ DOT_BEFORE_MORE_NUMBERS
+ "){4}$";
Upvotes: 1
Reputation: 784998
You can use this regex to allow white spaced anywhere in an IP address:
^\s*([0-9]{1,3}\s*\.\s*){3}[0-9]{1,3}\s*$
Upvotes: 3