All Those Other String Functions Are Handy, Too

There are numerous other string manipulation functions that can be used when working with patterns. For example, in Chapter 3 (p. 77), I used "string trimright" to remove all the newline characters from the end of a string.

Another function that is very handy is scan. The scan command interprets strings according to a format. scan is analogous to the C language scanf function. For the most part, scan is less powerful than regexp, but occasionally the built-in capabilities of scan provide exactly the right tool. For example, a regular expression to match a C-style real number is:

([0-9]+.?[0-9]*|[0-9]*.[0-9]+)([eE][-+]?[0-9]+)?

And that is before adding the backslashes in front of "[“, "." and "+“! A much better alternative is to use Tcl’s scan command. This can match real numbers, plus you can constrain it for precision. All you have to do is feed it a string containing a number. You can have expect look for the end of the number (such as by seeing whitespace) and then call:

scan $expect_out(string,0) "%f" num

In this example, the number is stored in the variable num. The %f tells scan to extract a real number. Chapter 2 (p. 46) has more information on scan and other string manipulation commands.

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.