More Glob Patterns

In all the examples so far using the * wildcard, it has matched an arbitrarily long string of characters. This kind of pattern specification is called shell-style since it is similar to the way filename matching works in the shell. The name of the program which did this matching for the Bourne shell was called glob. Hence such patterns are often called glob-style also. From now on, I will just call them glob patterns.

Tcl’s "string match" command also uses glob patterns. Glob patterns support two other wildcards. They are "?" and "[]“.

? matches any single character. For example, the pattern a?d would match abd but not abcd.

Ranges match any character specified between square brackets. For example, [abcdef0123456789] matches any hexadecimal digit. This pattern can also be expressed as [a-f0-9]. If you want to match a literal hyphen, make it the first or last character. For example, [-a-c] matches "-“, "a“, "b“, or "c“.

Unfortunately, brackets are also special to Tcl. Anything in brackets is evaluated immediately (unless it is deferred). That means that an expect command using a pattern with a range must be written in one of two ways:

expect "\[a-f0-9]"     ;# strongly preferred
expect {[a-f0-9]}

In the first case, the backslash (\) allows the bracket to be passed literally to the expect command, where it is then interpreted as the start of a range. In the second case, the braces force everything inside to be read as their literal equivalents. I prefer the first style—because in the second case, sequences such as \n and $pat embedded in braces are not processed but are taken as literal character sequences of \ and n and $ and p and a and t. This is usually not what is intended.

You can prefix the right bracket with a backslash if it makes you feel good, but it is not necessary. Since there is no matching left-hand bracket to be matched within the double-quoted string, nothing special happens with the right-hand bracket. It stands for itself and is passed on to the expect command, where it is then interpreted as the end of the range.

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.