Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint

8.3. Anchors

By default, if a pattern doesn't match at the start of the string, it can "float" on down the string trying to match somewhere else. But a number of anchors may be used to hold the pattern at a particular point in a string.

The caret[*] anchor (^) marks the beginning of the string, and the dollar sign ($) marks the end.[†] So, the pattern /^fred/ will match fred only at the start of the string; it wouldn't match manfred mann. And /rock$/ will match rock only at the end of the string; it wouldn't match knute rockne.

[*] Yes, you've seen the caret used in another way in patterns. As the first character of a character class, it negates the class. But outside of a character class, it's a metacharacter in a different way, being the start-of-string anchor. There are only so many characters, so you have to use some of them twice.

[†] Actually, it matches either the end of the string or at a newline at the end of the string. That's so you can match the end of the string whether it has a trailing newline or not. Most folks don't worry about this distinction much, but once in a while it's important to remember that /^fred$/ will match "fred" or "fred\n" with equal ease.


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial