Tcl_StringCaseMatch 中的转义方括号 [英] Escape square bracket in Tcl_StringCaseMatch

查看:41
本文介绍了Tcl_StringCaseMatch 中的转义方括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 C++ 代码中使用 Tcl_StringCaseMatch 函数进行字符串模式匹配.一切正常,直到输入模式或字符串具有 [] 括号.例如,像:

<前>str1 = pq[0]模式 = pq[*]

Tcl_StringCaseMatch 不起作用,即为上述输入返回 false.模式匹配中如何避免[]?

解决方案

问题是 [] 是模式匹配中的特殊字符.您需要使用反斜杠将它们转义以将它们视为普通字符

pattern="pq\\[*\\]"

我不认为这也应该影响字符串.双斜线的原因是您想将反斜线本身传递给 TCL 引擎.

对于普通读者:

[] 一般在 TCL 中有特殊的意义,除了他们在这里扮演的模式匹配角色 - 运行命令"(如 `` 或 $() 中的shells),但 [number] 将不起作用,并且括号被正常处理 - 因此字符串 str1 不需要在这里转义.

对于额外的混淆:

默认情况下,TCL 会将没有前面的 [] 解释为普通字符.我觉得这太混乱了,宁愿 TCL 抱怨括号不平衡.正如 OP 所提到的,这允许您放弃最后两个反斜杠并使用 "pq\\[*]".我不喜欢这种方式,而是明确表示两者都被正常对待,而不是通常的 TCL 方式,而是每个人都拥有自己的方式.

I am using Tcl_StringCaseMatch function in C++ code for string pattern matching. Everything works fine until input pattern or string has [] bracket. For example, like:

str1 = pq[0]    
pattern = pq[*]        

Tcl_StringCaseMatch is not working i.e returning false for above inputs. How to avoid [] in pattern matching?

解决方案

The problem is [] are special characters in the pattern matching. You need to escape them using a backslash to have them treated like plain characters

pattern= "pq\\[*\\]"

I don't think this should affect the string as well. The reason for double slashing is you want to pass the backslash itself to the TCL engine.

For the casual reader:

[] have a special meaning in TCL in general, beyond the pattern matching role they take here - "run command" (like `` or $() in shells), but [number] will have no effect, and the brackets are treated normally - thus the string str1 does not need escaping here.

For extra confusion:

TCL will interpret ] with no preceding [ as a normal character by default. I feel that's getting too confusing, and would rather that TCL complains on unbalanced brackets. As OP mentions though, this allows you to forgo the final two backslashes and use "pq\\[*]". I dislike this, and rather make it obvious both are treated normally and not the usual TCL way, but to each her/is own.

这篇关于Tcl_StringCaseMatch 中的转义方括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆