Roy Zou
Roy Zou

Reputation: 13

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?

Upvotes: 1

Views: 1355

Answers (2)

Mario Santini
Mario Santini

Reputation: 3003

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]

Upvotes: 2

Israel Unterman
Israel Unterman

Reputation: 13510

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.

Upvotes: 0

Related Questions