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:



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):
        return True
        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?

Have a comment on one of my posts? Start a discussion in my public inbox by sending an email to ~sircmpwn/public-inbox@lists.sr.ht [mailing list etiquette]

Articles from blogs I read Generated by openring

SourceHut API 2.0 dev log

Completing the project now known as “API 2.0” is one of the most important steps in finalizing the sr.ht beta, and I’ve been trying to keep the community abreast of developments, especially on the sr.ht-dev mailing list. I’m summarizing for the blog as well t…

via Blogs on Sourcehut September 25, 2020

People expect technology to suck because it actually sucks

I get at least 27 tech annoyances on a single day

via tonsky.me September 25, 2020

Rewriting the Technical Interview

Frigitt, vi danser For et øyeblikk, vi leker Vi tusen små bladskiper Gleder oss, på det klare morgenlys The mothercone unfurls her softening scales, and in the time of days I am emancipated. Adrift in the chill dawn light, my siblings flutter, slender forms c…

via Aphyr: Posts September 18, 2020