Using Parentheses For Feedback

In the previous section, parentheses were used to group subpatterns together. Parentheses also play another role—a role that leads to much shorter scripts than would otherwise be possible. When a regular expression successfully matches a string in the input buffer, each part of the string that matches a parenthesized subpattern is saved in the array expect_out. The string that matches the first parenthesized subpattern is stored in "expect_out(1,string)“. The string that matches the second is stored in "expect_out(2,string)“. And so on, up to "expect_out(9,string)“.

For example, suppose you want to know the characters that occur between two other characters. If the input buffer contains "junk abcbcd" and I use the pattern "a(.*)c“, this matches the input buffer and so expect makes the following assignment:

set expect_out(1,string) "bcb"

expect also stores the string that matches the entire pattern in "expect(0,string)“:

set expect_out(0,string) "abcbc"

Finally, expect stores the whole string that matches the entire pattern as well as everything that came before it in expect_out(buffer):

set expect_out(buffer) "junk abcbc"

The "d" in the input buffer was never matched, so it remains there.

The last two assignments (to expect_out(buffer) and expect_out(0,string)) occur with glob patterns as well.

The values of expect_out are never deleted but can be overwritten by new expect commands. Assuming that the input buffer holds "junk abcbcd“, the following sequence ...

Get Exploring Expect now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.