在操作数字符串中包含方括号时出现字符串匹配问题
Issue with string match when having square brackets in the operands strings
这看起来符合预期:
set a 1
puts [string match $a $a]
>> 1
然而我发现这出乎意料:
set b {[1]}
puts [string match $b $b]
>> 0
你能帮忙解释一下上面的行为吗?
模式[1]
是匹配括号内字符的括号表达式。在这种情况下,唯一匹配模式的字符串是 1
.
% set b {[1]}
[1]
% puts [string match $b $b]
0
% puts [string match $b "1"]
1
%
如果您想比较两个字符串以查看它们是否相同,请改用 string equal ...
。
如果您在 unix shell 环境中,man n string
或 man 3tcl string
应该会显示一个手册页,其中包含有关 string
命令的详细信息。
这看起来符合预期:
set a 1
puts [string match $a $a]
>> 1
然而我发现这出乎意料:
set b {[1]}
puts [string match $b $b]
>> 0
你能帮忙解释一下上面的行为吗?
模式[1]
是匹配括号内字符的括号表达式。在这种情况下,唯一匹配模式的字符串是 1
.
% set b {[1]}
[1]
% puts [string match $b $b]
0
% puts [string match $b "1"]
1
%
如果您想比较两个字符串以查看它们是否相同,请改用 string equal ...
。
如果您在 unix shell 环境中,man n string
或 man 3tcl string
应该会显示一个手册页,其中包含有关 string
命令的详细信息。