Sasa Stamenkovic
Sasa Stamenkovic

Reputation: 95

Check if string end with substring, Tcl

I have a searching string .state_s[0] and another two lists of strings:

{cache.state_s[0]} {cache.state_s[1]}

and

{cache.state_s[0]a} {cache.state_s[1]}

I need command(s) Tcl interpreter accepts to ask if the searching string is matching any of the items in the string list. What is also very important, the solution should only return positive result for the first list. I tried:

set pattern {.state_s[0]}
set escaped_pattern [string map {* \\* ? \\? [ \\[ ] \\] \\ \\\\} $pattern]
set m1 {{cache.state_s[0]} {cache.state_s[1]}}
set m2 {{cache.state_s[0]a} {cache.state_s[1]}}
regexp $escaped_pattern $m1
regexp $escaped_pattern $m2

However, the above commands are returning "1" with both regexp calls.

Basically, I need a way to check if a substring (having special chars like [) is at the end of a string.

Upvotes: 0

Views: 1844

Answers (1)

Dinesh
Dinesh

Reputation: 16428

You have the elements as a list in a variable m1.

set m1 {{cache.state_s[0]} {cache.state_s[1]}}
set m2 {{cache.state_s[0]a} {cache.state_s[1]}}

But, when you apply it against regexp, Tcl will treat the input m1 as a whole string, not a list.

Since both the list contains the string .state_s[0], regexp returning the result as 1.

If you want to apply the regular expression for each element, then I would recommend to use the lsearch with -regexp flag.

% set m1 {{cache.state_s[0]} {cache.state_s[1]}}
{cache.state_s[0]} {cache.state_s[1]}
% set m2 {{cache.state_s[0]a} {cache.state_s[1]}}
{cache.state_s[0]a} {cache.state_s[1]}
%
% lsearch -regexp -inline $m1 {\.state_s\[0]$};
cache.state_s[0]
% lsearch -regexp -inline $m2 {\.state_s\[0]$}
%

The pattern I have used here is {\.state_s\[0]$}. The last $ symbol represents end of line. With this, we are ensuring that the element doesn't have any more characters in it. We don't have escape the closing square bracket ] in Tcl.

Upvotes: 1

Related Questions