Tcl/Tk Notes (2)

本文介绍Tcl中的字符串处理方法,包括字符串命令的使用、表达式的比较、格式化输出、扫描输入、模式匹配及正则表达式的应用。通过具体示例展示了如何进行字符串比较、格式化字符串、解析字符串、模式匹配及替换等操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 &.
内容概要:本文档是关于基于Tecnomatix的废旧智能手机拆解产线建模与虚拟调试的毕业设计任务书。研究内容主要包括:分析废旧智能手机拆解工艺流程;学习并使用Tecnomatix软件搭建拆解产线的三维模型,包括设备、输送装置等;进行虚拟调试以模拟各种故障情况,并对结果进行分析提出优化建议。研究周期为16周,涵盖了文献调研、拆解实验、软件学习、建模、调试和论文撰写等阶段。文中还提供了Python代码来模拟部分关键流程,如拆解顺序分析、产线布局设计、虚拟调试过程、故障模拟与分析等,并实现了结果的可视化展示。 适合人群:本任务书适用于机械工程、工业自动化及相关专业的本科毕业生,尤其是那些对智能制造、生产线优化及虚拟调试感兴趣的学生。 使用场景及目标:①帮助学生掌握Tecnomatix软件的应用技能;②通过实际项目锻炼学生的系统建模和虚拟调试能力;③培养学生解决复杂工程问题的能力,提高其对废旧电子产品回收再利用的认识和技术水平;④为后续的研究或工作打下坚实的基础,比如从事智能工厂规划、生产线设计与优化等工作。 其他说明:虽然文中提供了部分Python代码用于模拟关键流程,但完整的产线建模仍需借助Tecnomatix商业软件完成。此外,为了更好地理解和应用这些内容,建议学生具备一定的编程基础(如Python),并熟悉相关领域的基础知识。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值