Anchoring
Finding unexpected data in the input does not bother expect. It keeps looking until it finds something that matches. It is possible to prevent expect from matching when unexpected data arrives before a pattern. The caret (^) is a special character that only matches the beginning of the input. If the first character of the pattern is a caret, the remainder of the pattern must match starting at the beginning of the incoming data. It cannot skip over characters to find a valid match. For example, the pattern ^hi matches hiccup but not sushi.
The dollar sign ($) is another special character. It matches the end of the data. The pattern hi$ matches sushi but not hiccup. And the pattern ^hi$ matches neither sushi nor hiccup. It matches hi and nothing else.
Patterns that use the ^ or $ are said to be anchored. Some programs, such as sed, define anchoring in terms of the beginning of a line. This makes sense for sed, but not for expect. expect anchors at the beginning of whatever input it has received without regard to line boundaries.
When patterns are not anchored, patterns match beginning at the earliest possible position in the string. For example, if the pattern is hi and the input is philosophic, the hi in philo is matched rather than the hi in sophic. In the next section, this subtlety will become more important.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access