Every Time You Write a Regular Expression You Should Be Required to Put Sample Input in a Comment

There's a reason PERL has a reputation for being unreadable: regular expressions are almost impossible to decipher without any context.

Consider seeing the following in a python script:

conf_regex = " *(\d+) +(\d+\.\d+\.\d+\.\d+)/(\d+) +(\d+\.\d+\.\d+\.\d+) +(\d+) +(.+) *"

From the variable name you can infer it's being used to parse a conf file, but that's about it.  Now compare that to the following:

# regex for parsing conf file, example entry below
# #id     network             addr        port    connections
# 0       155.246.80.0/24     127.0.0.1   5000    0,3
conf_regex = " *(\d+) +(\d+\.\d+\.\d+\.\d+)/(\d+) +(\d+\.\d+\.\d+\.\d+) +(\d+) +(.+) *"

Suddenly it's not so bad.

Comments

Popular posts from this blog

Terminate Scripted Minicom Session

What Twitter Tells Us

CodinGame: Building an AI to play (and win) at "Penguins"