tcl: regexp matching special character

Hello Experts,

Can someone help me here:

I have a variable which contains a string with "[]".

set var1 {a[1]}
set str1 {a[1] is the element i want to match}

Now "regexp $var1 $str1" does not work?
("regexp {a\[1\]} $str1" works, but var1 gets it's value automatically from another script)

Is there a way to make it work?
(adding backslash "\" to var1 might not be feasible)

% regexp {[$var1]} $str1
1

Can you explain 'How it works?'?

It doesn't seem right to me.

% set var1 {a[1]}
a[1]
% set str1 {a[1] is the element i want to match}
a[1] is the element i want to match
% regexp $var1 $str1
0
% regexp {[$var1]} $str1
1
% set var1 {a[10]}
a[10]
% regexp {[$var1]} $str1
1
% set var1 {a[9080]}
a[9080]
% regexp {[$var1]} $str1
1

If you want a substring exact match that doesn't really rely on regexp syntax look at string match instead, but ymmv. I'm having trouble obtaining a sane result.You can always brute force the search..something like.

proc paramSearch {pattern str} {
set t [string length $pattern]
                for {set i 0} {$i < [string length $str]} {incr i $t} {
                    if {[string compare $pattern [string range $str $i [expr $i + [ expr $t - 1]]]] == 0} {return 1; #puts "Match at string index: $i"}
                    #puts "Compared $pattern and [string range $str $i [expr $i + [ expr $t - 1]]]"
                }
}
() 92 % set vv
thisis[]a[1]test
() 93 % set pat
a[1]
() 94 % paramSearch $pat $vv
1

Off by one...

proc paramSearch {pattern str} {
set t [expr [string length $pattern] - 1]
                for {set i 0} {$i < [string length $str]} {incr i $t} {
                    if {[string compare $pattern [string range $str $i [expr $i + $t]]] == 0} {return 1; #puts "Match at string index: $i"}
                    #puts "Compared $pattern and [string range $str $i [expr $i + $t]]"
                }
}

i was trying to understand if (and how) that can be done with 'regexp'?

Otherwise,

lsearch -exact $str1 $var1

does the job pretty well.

% set var1 {a[1]}
a[1]
% set var2 {aa[1]}
aa[1]
% set var3 {a[11]}
a[11]
% set str1 {a[1] is the element we are looking for and not aa[1] or a[11]}
a[1] is the element we are looking for and not aa[1] or a[11]

% lsearch -exact $str1 $var1
0
% lsearch -exact $str1 $var2
10
% lsearch -exact $str1 $var3
12

I can't make the regexp code behave as anticipated, thus the workaround.
Worse, the string match code seems fundamentally unhappy with brackets.

I'd approach comp.lang.tcl with this issue and/or check out the tclers wiki and
see if any articles are on point. The Tcler's Wiki
The lsearch idea is a okay but forces an abstraction from one
implicit type to another without solving the underlying problem and
possibly causing others...