1

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

Josua Marcel C
  • 3,122
  • 6
  • 45
  • 87
misbha afreen
  • 33
  • 1
  • 6

5 Answers5

1

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)

Prabhakaran
  • 3,900
  • 15
  • 46
  • 113
0

Look at the pre-made regular expressions provided by these Perl modules.

Regexp::Common::net

Regexp::Common::net::CIDR

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.

lordadmira
  • 1,807
  • 5
  • 14
0

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: \/.

Tranbi
  • 11,407
  • 6
  • 16
  • 33
0

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}$

by josuamarcelc

Josua Marcel C
  • 3,122
  • 6
  • 45
  • 87
0

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}}
"""
Baris Ozensel
  • 433
  • 1
  • 3
  • 11