Part II Strings and Pattern Matching
1 The string Command
The general syntax of the Tcl
string command is:
string operation stringvalue otherargs
string operation stringvalue otherargs
2 Strings and Expressions
Strings can be compared with expr using the comparison operators.However, there're a number of subtle issues that can cause problems.
First, you must quote the string value so the expression parser can identify it as a string.
Second, you must quote the expression with curly braces to preserve the double quotes from being stripped off by the main interpreter.
In spite of the quotes the expression evaluation first converts things to numbers if possible, and then converts them back if it detects a case of string comparison. This can lead to unexpected conversions between strings that look like hex or octal numbers.
e.g. if {"0x0a"=="10"} {puts stdout ack!}
=> ack!
As a result, the only bombproof way to compare strings is with the string compare command. This command also operates quite a bit faster because the unnecessary conversoions are eliminated.
e.g. if {[string compare $s1 $s2]==0}{
# strings are equal
}
First, you must quote the string value so the expression parser can identify it as a string.
Second, you must quote the expression with curly braces to preserve the double quotes from being stripped off by the main interpreter.
In spite of the quotes the expression evaluation first converts things to numbers if possible, and then converts them back if it detects a case of string comparison. This can lead to unexpected conversions between strings that look like hex or octal numbers.
e.g. if {"0x0a"=="10"} {puts stdout ack!}
=> ack!
As a result, the only bombproof way to compare strings is with the string compare command. This command also operates quite a bit faster because the unnecessary conversoions are eliminated.
e.g. if {[string compare $s1 $s2]==0}{
# strings are equal
}
3 The format Command
The
format command is similar to the C
printf function. It formats a string according to a format specification:
format spec value1 value2 ...
format spec value1 value2 ...
A position specifier is
i$, which means take the value from argument
i as opposed to the normally corresponding argument. The position counts from 1. If you group the format specification with double-quotes, you will need to quote the $ with a backslash.
e.g. set lang 2
format "%${lang}/$s" one un uno
=> un
In the above example, the second line prints the second string--un.
If a position is specified for one format keyword, it must be used for all of them.
e.g.
format "%#08x" 10
=> 0x0000000a
You can comupte a field width and pass it to format as one of the arguments by using * as the field width specifier. In this case the next argument is used as the field width instead of the value, and the argument after that is the value that gets formatted.
e.g.
set maxl 8
format "%-*s=%s" $maxl Key Value
=> Key =Value (Five spaces)
scan string format var ?var? ?var?...
There's no %u scan format. The %c scan format converts one character to its binary value.
The scan format includes a set notation. Use square brackets to delimit a set of characters. The set matches one or more characters that are copied into the variable. A dash is used to specify a range.
e.g.
scan abcABC {%[a-z]} result
=> 1
set result
=>abc
If the first character in the set is a right square bracket, then it is considered part of tje set. If the first character in the set is ^, then characters
not in the set match. Again, put a right square bracket right after the ^ to include it in the set. Nothing special is required to include a left square bracket in the set. You can protect the format with braces, or use backslashes, because square brackets are special to the Tcl parser.
e.g. set lang 2
format "%${lang}/$s" one un uno
=> un
In the above example, the second line prints the second string--un.
If a position is specified for one format keyword, it must be used for all of them.
format "%#08x" 10
=> 0x0000000a
You can comupte a field width and pass it to format as one of the arguments by using * as the field width specifier. In this case the next argument is used as the field width instead of the value, and the argument after that is the value that gets formatted.
e.g.
set maxl 8
format "%-*s=%s" $maxl Key Value
=> Key =Value (Five spaces)
4 The scan Command
The scan command is like the C sscanf procedure. It parses a string according to a format specification and assigns values to variables. It returns the number of successful conversions it made. The general form of command is given below:
scan string format var ?var? ?var?...
There's no %u scan format. The %c scan format converts one character to its binary value.
The scan format includes a set notation. Use square brackets to delimit a set of characters. The set matches one or more characters that are copied into the variable. A dash is used to specify a range.
e.g.
scan abcABC {%[a-z]} result
=> 1
set result
=>abc
5 String Matching
There are 3 constructs used in pattern matching: *, ? and [ abc ].To match all strings that begin with either a or b:
string match {[ab]*} cello
=>0
Square brackets are special to Tcl interpreter, so you need to wrap the pattern up in curly braces to prevent it from being interpreted as a nested command.
6 Regular Expressions
A pattern is a sequence of a literal character, a matching character, a repetition clause, an alternation clause, or a sub pattern grouped with parentheses.
ba*
While the following matches a string that has one or more sequences of ab:
(ab)+
The pattern that matches anything is :
.*
In general, apattern does not have to match the whole string. If you need more control than this, then you can anchor the pattern to the beginning of the string bu starting the pattern with ^, or to the end of the string by ending the pattern with $. You can force the pattern to match the whole string by using both. All strings that begin with spaces or tabs are matched with the following:
^( |/t)+
The rule of thumb is "First, then longest".
7 The regexp Command
The regexp command provides direct access to the regular expression matcher:regexp ?flags? pattern string ?match sub1 sub2...?
The return value is 1 if some part of the string matches the pattern, it is 0 otherwise.
The pattern argument is a regular expressiona s described in the previous section. If this contains $ or [, you have to be careful. The easiest way is group your patterns with curly braces. However, if your patterns contains backslash sequences like /n or /t you will have to group with double quotes so the Tcl interpreter can do those substitutions. You will have to use /[ and /$ in youe patterns in that case.
If string matches pattern, then the result of the match are stored into the variables named in the command. These match variable arguments are optional. If present, match is set to be the part of the string that matched the pattern. The remaininng variables are set to be the substring of string that matched the corresponding subpatterns in the pattern. The correspondence is based on the order of left parentheses in the pattern to avoid ambiguities that can arise from nested subpatterns.
e.g.
set env(DISPLAY) corvina:0.1
regexp {([^:]*):} $env(DISPLAY) match host
=> 1
set match
=>corvina:
set host
=> corvina
The pattern involves a complementary set,[^:], to match anything except a colon. It uses repetition, *, to repeat that zero or more times. Then, it groups that part into a subexpression with parentheses. The literal colon ensures that the DISPLAY value matches the format we expect. The part of the string that matches the pattern will be stored into the match variable. The part that we really want is what matches the subpattern, and tha twill be stored into host. The whole pattern has been grouped with braces to avoid tha special meaning of the square brackets to the Tcl interpreter.
Mutilple subpatterns are allowed. The improved pattern is:
regexp {([^:]*):(.+)} $env(DISPLAY) match host screen
=> 1
set match
=> corvina:0.1
set host
=> corvina
set screen
=> 0.1
regsub ?switches? pattern string subpec varname
The regsub command returns the number of matches and replacements, or 0 if there was no match. regsub copies string to varname, replacing occurrences of pattern with the substitution speciafied by subspec.
The optional switches include -all, which means to replace all occurrences of the pattern. Otherwise only the first occurrence is replaced. The -nocase switch means that upper-case characters in the string are converted to lowercase before matching. The -- switch is useful if your pattern begins with -.
cc -c file.c -o file.o
With an input pattern of file.c and a pattern of {([^/.]*)/.c}, the subpattern matches everything up to the first period in the input, or just file. the replacement pattern, {cc –c & -o /1.o},references the subpattern match with /1, and the whole match with &.
set env(DISPLAY) corvina:0.1
regexp {([^:]*):} $env(DISPLAY) match host
=> 1
set match
=>corvina:
set host
=> corvina
The pattern involves a complementary set,[^:], to match anything except a colon. It uses repetition, *, to repeat that zero or more times. Then, it groups that part into a subexpression with parentheses. The literal colon ensures that the DISPLAY value matches the format we expect. The part of the string that matches the pattern will be stored into the match variable. The part that we really want is what matches the subpattern, and tha twill be stored into host. The whole pattern has been grouped with braces to avoid tha special meaning of the square brackets to the Tcl interpreter.
Mutilple subpatterns are allowed. The improved pattern is:
regexp {([^:]*):(.+)} $env(DISPLAY) match host screen
=> 1
set match
=> corvina:0.1
set host
=> corvina
set screen
=> 0.1
8 The regsub Command
The regsub command is used to do string substitution based on pattern matching:regsub ?switches? pattern string subpec varname
The regsub command returns the number of matches and replacements, or 0 if there was no match. regsub copies string to varname, replacing occurrences of pattern with the substitution speciafied by subspec.
The optional switches include -all, which means to replace all occurrences of the pattern. Otherwise only the first occurrence is replaced. The -nocase switch means that upper-case characters in the string are converted to lowercase before matching. The -- switch is useful if your pattern begins with -.
The replacement pattern, subspec, can contain literal characters as well as the following special sequences:
- & is replaced with the string that matched the pattern.
- /1 through /9 are replaced with the strings that match the corresponding subpatterns in pattern. As with regexp, the correspondence is based on the order of left parentheses in the pattern specification.
The following is used to replace a user’s home directory with a ~:
regsub ^$env(HOME)/ $pathname ~/ newpath
The following is used to construct a C compile command line given a filename. The /. Is used to specify a match against period.
regsub {([^/.]*)/.c} file.c {cc –c & -o /1.o} ccCmd
The value assigned to ccCmd is :cc -c file.c -o file.o
With an input pattern of file.c and a pattern of {([^/.]*)/.c}, the subpattern matches everything up to the first period in the input, or just file. the replacement pattern, {cc –c & -o /1.o},references the subpattern match with /1, and the whole match with &.