DEV Community

Discussion on: What are your code smells and/or best practices with regular expressions?

Collapse
 
recursivefaults profile image
Ryan Latta

Yes!

I personally see regular expressions no better than a magic string. They stand out in code like a sore spot in your mouth. The more that regex tries to do the more that sore hurts and paradoxically becomes something you keep on agitating.

My approach with regexes, if I truly decide they are needed, focuses on creating progressive filters. I'll use regexes that progressively hone in on what I am exactly looking for.

I don't use regexes for validation. Creating a correct regex that validates anything is way harder than it seems, and the result is confusing and unmaintainable.

Collapse
 
gsonderby profile image
Gert Sønderby

I saw a regex for validating an SMTP adress once, and it was a glorious, ridiculous piece of work. Something like 600 or 700 characters worth. Pretty sure that represents an anti-pattern! :-P

I mainly use regexes for searching/replacing, or for testing for presence of specific fragments. A common one for me is checking to see if a link URL is an absolute address, a mail address or a relative path, for example. Simple, and reasonable.