简体   繁体   English

当搜索字符串包含变量和空格时,如何使用Tcl regexp?

[英]How to use Tcl regexp when the search string contains variables and spaces?

Here's the code where I would like to match $line with $ram using Tcl regexp . 这是我想使用Tcl regexp$line$ram匹配的代码。

set line {      0    DI   /hdamrf};
set ram {/hdamrf};
regexp {\s+\d\s+DI\s+$ram} $line match; ## --> 0

Please help me construct a search string which can match the regular expression. 请帮助我构造一个可以匹配正则表达式的搜索字符串。 It so happens that to use variables in search strings they have to be enclosed in curly braces. 碰巧在搜索字符串中使用变量时,必须将它们括在花括号中。 But curly braces doesn't allow me to use \\s for detecting white space. 但是花括号不允许我使用\\s来检测空白。 Thanks. 谢谢。

This is one possibility: 这是一种可能性:

regexp [format {\s+\d\s+DI\s+%s} $ram] $line match

This is another: 这是另一个:

regexp "\\s+\\d\\s+DI\\s+$ram" $line match

Documentation: format , Syntax of Tcl regular expressions , regexp 文档: 格式Tcl正则表达式的语法regexp

Try it this way: 尝试这种方式:

regexp [subst -nocommands -nobackslashes {\s+\d\s+DI\s+$ram}] $line match

For example: 例如:

% regexp [subst -nocommands -nobackslashes {\s+\d\s+DI\s+$ram}] $line match
1

See the manual page for subst here :; 请参阅手册页subst 这里 :;

This command performs variable substitutions, command substitutions, and backslash substitutions on its string argument and returns the fully-substituted result. 该命令对其字符串参数执行变量替换,命令替换和反斜杠替换,并返回完全替换的结果。 The substitutions are performed in exactly the same way as for Tcl commands. 替换的执行方式与Tcl命令完全相同。 As a result, the string argument is actually substituted twice, once by the Tcl parser in the usual fashion for Tcl commands, and again by the subst command. 结果,字符串参数实际上被替换了两次,一次是由Tcl解析器以通常的方式替换为Tcl命令, subst一次是由subst命令。

If any of the -nobackslashes , -nocommands , or -novariables are specified, then the corresponding substitutions are not performed. 如果指定了-nobackslashes-nocommands-novariables中的任何一个,则不会执行相应的替换。 For example, if -nocommands is specified, command substitution is not performed: open and close brackets are treated as ordinary characters with no special interpretation. 例如,如果指定了-nocommands ,则不执行命令替换: -nocommands括号和-nocommands括号被视为普通字符,没有特殊解释。

Since it's already in {...} , the part about the parser interpreting it twice isn't completely accurate :) 由于它已经在{...} ,因此有关解析器两次解释的部分并不完全准确:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM