RegEx shortcuts for working with Classless Internet Domain Routing (CIDR)

I haven’t seen these posted anywhere, so I figured I would share. Here are some RegEx shortcuts for working with various CIDR blocks. They aren’t the most concise, but they are readable which is important to me when cobbling together complex combinations. They are POSIX regex so they should work in a bunch of places like egreps and MySQL REGEXPs.

=====
/19
=====
0-31
([12]?[0-9]|3[01])

32-63
(3[2-9]|[45][0-9]|6[0-3])

64-95
(6[4-9]|[78][0-9]|9[0-5])

96-127
(9[6-9]|1[01][0-9]|12[0-7])

128-159
(12[89]|1[3-5][0-9])

160-191
(1[6-8][0-9]|19[01])

192-223
(19[2-9]|2[01][0-9]|22[0-3])

224-255
(22[4-9]|2[34][0-9]|25[0-5])

=====
/18
=====
0-63
([1-5]?[0-9]|6[0-3])

64-127
(6[4-9]|[7-9][0-9]|1[01][0-9]|12[0-7])

128-191
(12[89]|1[3-8][0-9]|19[01])

192-255
(19[2-9]|2[0-4][0-9]|25[0-5])

=====
/17
=====
0-127
([1-9]?[0-9]|1[01][0-9]|12[0-7])

128-255
(12[89]|1[3-9][0-9]|2[0-4][0-9]|25[0-5])

=====
/16
=====
0-255
([1-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])

Advertisements

3 Responses to RegEx shortcuts for working with Classless Internet Domain Routing (CIDR)

  1. Arthur says:

    Here is a very useful regex for date:

    format: YYYY-MM-DD

    regex:^(19|20)[0-9]{2}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])
    ___________________
    Emergency Soft

  2. Jim McCullars says:

    Hey, thanks for publishing this. I did a Google search on cidr+regex and it brought me here. This was exactly what I was looking for.

  3. Richdad says:

    Just like Jim said, I googled regex cidr and Google brought me here đŸ™‚
    Just what I been looking for. My htaccess mod_rewrite for ip blocks contains
    errors where there are C-blocks that should be included but inserted without using proper CIDR regex.

    This comes in handy. Big thanks!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: