When not to use a regex August 13, 2017 on Drew DeVault's blog

The other day, I saw Learn regex the easy way. This is a great resource, but I felt the need to pen a post explaining that regexes are usually not the right approach.

Let’s do a little exercise. I googled “URL regex” and here’s the first Stack Overflow result:

https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)

source

This is a bad regex. Here are some valid URLs that this regex fails to match:

Here are some invalid URLs the regex is fine with:

This answer has been revised 9 times on Stack Overflow, and this is the best they could come up with. Go back and read the regex. Can you tell where each of these bugs are? How long did it take you? If you received a bug report in your application because one of these URLs was handled incorrectly, do you understand this regex well enough to fix it? If your application has a URL regex, go find it and see how it fares with these tests.

Complicated regexes are opaque, unmaintainable, and often wrong. The correct approach to validating a URL is as follows:

from urllib.parse import urlparse

def is_url_valid(url):
    try:
        urlparse(url)
        return True
    except:
        return False

A regex is useful for validating simple patterns and for finding patterns in text. For anything beyond that it’s almost certainly a terrible choice. Say you want to…

validate an email address: try to send an email to it!

validate password strength requirements: estimate the complexity with zxcvbn!

validate a date: use your standard library! datetime.datetime.strptime

validate a credit card number: run the Luhn algorithm on it!

validate a social security number: alright, use a regex. But don’t expect the number to be assigned to someone until you ask the Social Security Administration about it!

Get the picture?

Articles from blogs I read Generated by openring

The Future of Forums is Lies, I Guess

In my free time, I help run a small Mastodon server for roughly six hundred queer leatherfolk. When a new member signs up, we require them to write a short application—just a sentence or two. There’s a small text box in the signup form which says: Please t…

via Aphyr: Posts July 7, 2025

Raised Catholic

My introduction to CatholicismIn my young life, I was quite involved in Catholicism. I was raised this way by my mother, who wholeheartedly believes in it. In contrast, my father is not religious, and only goes to church for special occasions like the Chr…

via Cadence's Weblog July 6, 2025

Hare 0.25.2 released

I am pleased to announce the release of Hare 0.25.2 today. 🎉 It has been almost one year since the previous release, Hare 0.24.2, and the new release is packed with the numerous language features, standard libarary features, and countless bugfixes and small…

via Blogs on The Hare programming language June 21, 2025