Regular Expression Patterns

Regular expressions can be identified with exp_regexp. Here is the first example from page 494, rewritten to use a regular expression pattern:

exp_expectl(fd, exp_regexp, "prompt.*", 1, exp_end);

The type of all patterns are always identified explicitly, so different pattern types can be mixed without confusion. Here is an expect call with both glob and regular expression patterns:

exp_expectl(fd ,exp_regexp, "prompt.*", 1,
                exp_glob, "another pattern", 2,
                exp_regexp, "and another", 3,
                exp_end);

Caching Regular Expressions

The regular expression implementation used by Expect converts the pattern to an internal form that allows strings to be tested very quickly. The conversion procession is known as compilation. The compilation itself can cost more in terms of time than is saved later during the pattern matching. But if the pattern is going to be used more than once, compilation can ultimately save a great deal of time.

In the examples so far, the expect functions compile the regular expressions internally. Because input usually arrives slowly, patterns get evaluated many times and the compilation process pays off and time is saved. However, the compiled form is discarded at the end of each expect function. If the function is in a tight loop, this can be wasteful.

You can pass the compiled form to the expect functions by using exp_compiled instead of exp_regexp. Assuming the compiled form is stored in fastprompt, the earlier example might be rewritten this ...

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.