The caret (^) is the starting anchor, and the dollar sign ($) is the end anchor. The regular expression ^A will match all lines that start with an uppercase A. The expression A$ will match all lines that end with uppercase A. If the anchor characters are not used at the proper end of the pattern, they no longer act as anchors. That is, the ^ is an anchor only if it is the first character in a regular expression. Both anchors together ^…$ are is used to test whether or not a string fully matches the pattern.

 

Example

Match for \d\d:\d\d must start exactly after the beginning of the text ^, and the end $ must immediately follow. The whole string must be exactly in this format. If there’s any deviation or an extra character, regex will not match with the string.

/^\d\d:\d\d$/  = "12:34";
/^\d\d:\d\d$/  ≠ "12:345";

 

Consider another example with regex ^4$ and expression 749\n486\n4 (\n represents a newline character) in multi-line mode.

Regex engine starts at the first character: 7. First token in the regular expression is ^, which is a zero-length token. So the regex engine skip ^ and advances to the next regex token: 4.  Regex engine compares 7 in the string with 4 is a literal character, which does not match 7.

Next engine starts again with the first regex token, at the next character: 4. ^ cannot match at the position before the 4 so engine continues at 9, and fails again and likewise for other character.

Now the regex engine arrives at the second 4 in the string and match with the regex token, 4. Since 4 matches 4, and the engine advances both the regex token and the string character. Now the engine attempts to match $ at the position before the 8. The dollar cannot match here, because this position is followed by a character, and that character is not a newline.

Finally regex matches the last string.