Regular Expression Anchor Mnemonic

In most languages, regular expressions have symbols to indicate when the first part or last part must match the first or last part of the string or line. These are called anchors. Anchors are usually the caret () for matching the beginning of a string, and the dollar sign ($) for the end of the string. Hence:

'abc' =~ /c$/     => true
'abc' =~ /a$/     => false
'abc' =~ /^a/     => true 
'abc' =~ /^c/     => false

I can remember what the anchors are. When I have trouble remembering which is which, I use the following mnemonic:

Regular expressions are perfect, like the Garden of Eden.

Snakes end the Garden of Eden.

In this case, the dollar sign looks a lot more like a snake than the caret does, so it’s the ending anchor. This might be corny, or perhaps not completely accurate to the original story or the true nature of regular expressions (hairy beasts that they are), but it’s served me pretty well.

Categories: development

« Free Software Documentation Annual Navel Gazing »