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.
previous post: Free Software Documentationnext post: Annual Navel Gazing
It’s funny you bring this up, because I have trouble remembering the function of these characters too. I first used regular expressions heavily with Perl which has $’s littered in front of scalars. I imagine both /$a/ and /a$/, but when I see /$a/ I think $a is a variable reference, so it must be /a$/.
Overly complicated? Yes, but it gets the job done!
I always remember that the caret is also used to represent control characters, as in ^M and comes at the beginning. And the last thing to happen after finishing work is that you are paid; hence, $ at the end.
Stupid, but it works for me.
@robbyslaughter
When I read this Monday morning I thought ‘heh, clever, but I never use RegEx’. Then Monday afternoon as I’m writing some RegEx I think to myself ‘which goes first? ^ or $ ?.
Thanks! Saved me from a quick google.