简体   繁体   English

tcl如何在正则表达式输出中处理方括号?

[英]how tcl handle square bracket in the regexp output?

I try to use regular expression command like: 我尝试使用正则表达式命令,例如:

IN: regexp -all -inline {\S+} "RR\[0\] in"
OUT:{RR[0]} in

But,when there is no square bracket in the string,the output format is different. 但是,当字符串中没有方括号时,输出格式会有所不同。

IN: regexp -all -inline {\S+} "RR in"
OUT:RR in

Why does the first element is between curly braces in the first case? 在第一种情况下,为什么第一个元素在花括号之间?

The issue is the square brackets are reserved in tcl for executing commands. 问题是在tcl中保留了方括号用于执行命令。

So it evaluate every square brackets found, included those inside strings delimited by " . 因此,它将评估找到的每个方括号,包括用分隔的字符串内的那些。

So when it returns the regexp matching it put the curling brackets to protect the string to be interpreted as containing a command. 因此,当它返回匹配的regexp时,将大括号括起来以保护字符串以将其解释为包含命令。

Even that, the results continue to be a string. 即使那样,结果仍然是字符串。

For example if you do that: 例如,如果您这样做:

% set r [regexp -all -inline {\S+} "RR\[0\] in"]
{RR[0]} in

And then you print from a loop: 然后从循环打印:

% foreach x $r { puts $x }
RR[0]
in

By the join command you could easily convert any kind of list into a string when you need, avoiding to remove the brackets with trim functions. 通过join命令,您可以在需要时轻松地将任何类型的列表转换为字符串,避免使用修饰功能删除括号。

% puts [join $r ]
RR[0] in

or direct to the element: 或直接指向元素:

% puts [join [lindex $r 0] ]
RR[0]

First, there is an error when you run the regexp the way it is. 首先,按原样运行regexp时出现错误。 It should be: 它应该是:

regexp -all -inline {\S+} {RR[0] in}

With braces around the string you search in. Because the square barckets are interpreted as a command, if you must tell tcl not to make a substitution, and one of the ways to tell it is by using braces. 使用大括号括住您要搜索的字符串。因为方括号被解释为命令,所以如果您必须告诉tcl不要进行替换,那么告诉它的一种方法是使用大括号。

Saying that, when the brackets do not exist, the regexp won't find them, of course. 说的是,当括号不存在时,正则表达式当然不会找到它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM