Tcl/Tk Notes (2)

Part II    Strings and Pattern Matching

1 The string Command

    The general syntax of the Tcl string command is:
        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
                }

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 ...
    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)

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
    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.

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.
    Repetition is specified with *, for zero-or-more; +, for one-or-more; and ?, for zero-or-one. The following matches a string that contains b followed by zero or more a's:
        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

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 &.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值