Let's look at some classical examples of RegEx.
Can you find a regex matching all integers from 0 to 255?
First, Let's look at how can we match all integers from 0 to 59:
As you can see, we have used ?
quantifier to make the first digit(0-5) optional. Now, can you solve it for 0-255?
Hint : Use OR operator.
We can divide the range 0-255 into three ranges: 0-199, 200-249 & 250-255. Now, creating an expression, for each of them independently, is easy.
Range | RegEx |
0-199 | [01][0-9][0-9] |
200-249 | 2[0-4][0-9] |
250-255 | 25[0-5] |
Now, by using OR operator, we can match the whole 0-255 range.
As you can see, the above regex is not going to match 0, but 000. So, how can you modify the regex which matches 0 as well, rather than matching 001 only?
We have just used ?
quantifier.
IP address consists of digits from 0-255 and 3 points(.
). Valid IP address format is
(0-255).(0-255).(0-255).(0-255).
For example, 10.10.11.4, 255.255.255.255, 234.9.64.43, 1.2.3.4 are Valid IP addresses.
Can you find a regex to match an IP-address?
We have already seen, how to match number ranges and to match a point, we use escaped-dot(\.
). But in IP address, we don't allow leading zeroes in numbers like 001.
So, We have to divide the range in four sub-ranges: 0-99, 100-199, 200-249, 250-255. And finally we use OR-operator.
So, Regex to match IP Address is as below:
Note: The whole expression is contiguous, for the shake of easy understanding it is shown the way it is.