I have a regex ^[a-zA-Z0-9.*?]+$
that supports IP addresses like 31.202.216.280
how can I modify the given regex in a way where I could support subnets with an IP address like so 31.202.216.280/38

- 3,122
- 6
- 45
- 87

- 33
- 1
- 6
5 Answers
Be careful, if you set [0-9]
for the Blocks, you can type an IPAddress with 999
as number.
If you want to "limit" to the 0-255 numbers, you need to explicit do this with:
^
(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.
(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.
(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.
(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\/
([1-3][0-2]$|[0-2][0-9]$|0?[0-9]$)
Makes it possible to write addresses with:
(0-255).(0-255).(0-255).(0-255)/(0-32)

- 3,900
- 15
- 46
- 113

- 11
- 1
Look at the pre-made regular expressions provided by these Perl modules.
You can use them on the command line or from a Perl script. You can also just copy the regex's and use them in another language.

- 1,807
- 5
- 14
With such a regex for IPs you might catch a lot of false positive. Try at least to remove a-ZA-Z
. There are already great regex on SO to match IPs.
If you want to match your subnet add /[0-9]{1,3}
before your string end ($
). You might need to escape the slash depending on your programming language: \/
.

- 11,407
- 6
- 16
- 33
if with regex subnet
^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\/[0-9]{1,3}$
if without subnet you may try
^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$

- 3,122
- 6
- 45
- 87
You can also use ttp template to capture IPs and PREFIXs as following. |IP
captures IPs, |PREFIX
captures prefixs.
See the following ttp example:
ttp_template = """
{{Prefix|PREFIX}}
{{Ip|IP}}
"""

- 433
- 1
- 3
- 11