Thursday, December 13, 2012

Keeping Regular with Regex


Keeping Regular with Regex

The first time I encountered Regex (Regular Expressions), I just shrugged it off as some overly complicated way of doing easy tasks such as simple control content validation. I did not fully understand the powerful capabilities, or what it could enable me to do.

Regex can be loosely defined as a syntax mechanism for searching or matching string patterns in a given string.

My standing with Regex quickly changed when I was tasked with creating user “Login History” logging functionality, which included the user’s IP.

At first I opted to validate the IP using substrings, splitting up the IP number into its four parts (IPv4) and then after converting it to integers, validate each part to the IP numerical ranges (0...255). To me this felt very messy, so I decided to do some research, and eventually rediscovered Regex for myself. Yet again this seemed to be very complicated, but I decided to take a closer look anyway.

Let’s take a look at the Expression that I ended up using:
\b(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]?)\b

This seems to be complicated, but breaking it down reveals its simplicity. It is the same pattern repeated four times separated by a literal ‘.’, in Regex ‘\.’.  The repeated pattern, ‘(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)’ has the simple task of validating the numerical values, 0 – 255.

This validation can be simplified as:
  • ·         25[0-5] - 250-255
  • ·         | - OR
  • ·         2[0-4][0-9] - 200-249
  • ·         | - OR
  • ·         [01]?[0-9][0-9]?) - 0-199


The reason for not just typing something like 0...255 is because Regex looks at the individual characters, and not numbers/strings as a whole.

This is one example of how Regex simplifies validation (for me anyway), but there are a lot of different uses for this powerful tool.


The goal here is not to teach the basics of Regex, but rather to open the mind to other possibilities or rather options to the way we code. You never know if there is something out there that could make your life as a developer easier if you are not willing to try new things.


No comments:

Post a Comment