Drektz
Drektz

Reputation: 95

Issue with string match when having square brackets in the operands strings

This looks as expected:

set a 1
puts [string match $a $a]
>> 1

However I find this unexpected:

set b {[1]}
puts [string match $b $b]
>> 0

Can you help explain the above behaviour?

Upvotes: 1

Views: 315

Answers (1)

rtx13
rtx13

Reputation: 2610

The pattern [1] is a bracket expression that matches the characters inside the brackets. In this case, the only string that will match the pattern is 1.

% set b {[1]}
[1]
% puts [string match $b $b]
0
% puts [string match $b "1"]
1
% 

If you'd like to compare two strings to see if they are identical, use string equal ... instead.

If you are in a unix shell environment, man n string or man 3tcl string should bring up a manual page with details about the string command.

Upvotes: 3

Related Questions