| [ Team LiB ] |
|
The regsub CommandThe regsub command does string substitution based on pattern matching. It is very useful for processing your data. It can perform simple tasks like replacing sequences of spaces and tabs with a single space. It can perform complex data transforms, too, as described in the next section. Its syntax is: regsub ?switches? pattern string subspec 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 specified by subspec. If the pattern does not match, then string is copied to varname without modification. The optional switches include:
The replacement pattern, subspec, can contain literal characters as well as the following special sequences:
The following replaces a user's home directory with a ~: regsub ^$env(HOME)/ $pathname ~/ newpath The following constructs a C compile command line given a filename:
set file tclIO.c
regsub {([^\.]*)\.c$} $file {cc -c & -o \1.o} ccCmd
The matching pattern captures everything before the trailing .c in the file name. The & is replaced with the complete match, tclIO.c, and \1 is replaced with tclIO, which matches the pattern between the parentheses. The value assigned to ccCmd is: cc -c tclIO.c -o tclIO.o We could execute that with: eval exec $ccCmd The following replaces sequences of multiple space characters with a single space:
regsub -all {\s+} $string " " string
It is perfectly safe to specify the same variable as the input value and the result. Even if there is no match on the pattern, the input string is copied into the output variable. The regsub command can count things for us. The following command counts the newlines in some text. In this case the substitution is not important:
set numLines [regsub -all \n $text {} ignore]
|
| [ Team LiB ] |
|