String Manipulation

format formatString [value ...]
Similar to the C function sprintf. The return value is the formatString with the %' sequences replaced with the values.
Example:
% set tot 123
% puts [format "Total amount: %4d" $tot]
regexp [-indices] [-nocase] [--] expr string [matchVar] [subVar ...]
Returns 1 if the regular expression expr matches the string, 0 if it doesn't. matchVar is filled with the substring that matches the entire expression; the subVar variables, instead, receive the strings that match the subexpression (defined with the parentheses).
Example:
% puts "match: $m, sub: $s"                   ;# s if empty
match: .c, sub: 
% regexp {.*/(.*)\.(.*)$} "/home/username/emacs.rc" m n e
1
% puts "match: $m, name: $n, ext: $e"

match: /home/username/emacs.rc, name: emacs, ext: rc
  • Use -nocase' for a case insensitive matching
  • Use -- to say that the following argument is the expression even if it starts with a dash -- (i.e. it's not an option)
regsub [-all] [-nocase] [--] expr string subSpec resultStr
As for regexp, a pattern matching on the string is performed using expr. The matching substrings are then replaced with the subSpec string and stored into resultStr.
Example:
% regsub , "a,b,c,d,e" \t res
1
% puts $res
a    b,c,d,e
% regsub -all , "a,b,c,d,e" \t res
4
% puts $res
a    b    c    d    e
  • If the -all' option is not selected only the first occurrence is replaced.
  • The return value is the number of matching substrings.
  • The -nocase and -- options work as for regexp
scan string format varName [varName ...]
Similar to the C function sscanf. Parses the fields of the string according to the format string. Each % sequence is stored in the corresponding varName. Returns the number of fields successfully parsed.
Example:
% set line "123 days, 12 hours"
% set form "%d days, %d hours"
% scan $line $form d h                        ;# d gets 123, h gets 12
string compare string1 string2
As for strcmp, returns
  • -1 if $string1 < $string2
  • 0 if $string1 == $string2
  • +1 if $string1 > $string2