简体   繁体   中英

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 .

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

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 :;

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

If any of the -nobackslashes , -nocommands , or -novariables are specified, then the corresponding substitutions are not performed. For example, if -nocommands is specified, command substitution is not performed: open and close brackets are treated as ordinary characters with no special interpretation.

Since it's already in {...} , the part about the parser interpreting it twice isn't completely accurate :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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