DEV Community

Discussion on: Do we need Regex?

Collapse
 
peledzohar profile image
Zohar Peled • Edited

IMHO, regular expressions are a very powerful tool that should be used only when needed.
Even though It has built in support in many programming languages, it is a language all by itself, and you need to be fluent in that language before you can use it all over the place.

Short, well documented regular expressions that saves you multiple lines of code are great and I do use them from time to time.

The most recent example was when I had to extract some data from a string provided by a 3rd party in the form of "id=value id=value" - the entire regular expression was short and sweet: "\s17=([+-]?\d+)\s"

On the other hand, long regular expressions are hard to read and maintain and I do prefer to write more lines of code for what I can get from a regular expression like that.
An example for this would have to be the regular expression recommended by Microsoft to validate an email address:

 @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
 @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-0-9a-z]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$"

This is something You'll never see in my code. Ever.

I would much rather suffering the few false positives the MailAddress constructor has than have to read that regular expression.