Is it possible to dynamically add flags to a command, without using eval?
For example, I wish to perform the following with a variable:
set isCaseSensitive 1
if {$isCaseSensitive == 1} {
set res [regexp -nocase -- $regexp $str]
} else {
set res [regexp -- $regexp $str]
}
# The following does NOT work
set regexp_flags ""
if {$isCaseSensitive == 1} {
append regexp_flags " -nocase"
}
set res [regexp $regexp_flags -- $regexp $str]
Using Tcl 8.5
Edit #1, 12:41 UTC:
(Response to the commenter Jerry)
I've executed the code:
set regexp_flags ""
if {$isCaseSensitive == 1} {
append regexp_flags "-nocase"
}
set res [regexp -line -all -inline -indices $regexp_flags -- $regexp $str]
And received the following error (omitted irrelevant text):
regexp match variables not allowed when using -inline
while executing
"regexp -line -all -inline -indices $regexp_flags -- $regexp $str"
That happens because that Tcl thinks that $str is a 4th parameter, which is forbidden while using the -inline flag.
See regexp command documentation.
Edit #2, 14:01 UTC:
Apparently for some reason, the non-printable characters that are in my subject string ($str) have some negative effect on this command. (Tcl isn't binary protected or something?)
I've tried to delete those characters before trying to regexp and it now works as expected.
set regexp_flags ""
if {$isCaseSensitive == 1} {
append regexp_flags "-nocase"
}
set str [regsub -all -- {[^[:print:]\t\n\r\f\v]} $str ""]
set res [regexp -line -all -inline -indices $regexp_flags -- $regexp $str]
append regexp_flags "-nocase"? It's working on my Tcl8.5. (inserting the space made it no more work)