简体   繁体   中英

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.

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.

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.

% 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. 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.

Saying that, when the brackets do not exist, the regexp won't find them, of course.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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