Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

lsearch with regexp not matching as anticipated when using start of pattern ^

36 views
Skip to first unread message

asilver

unread,
May 2, 2018, 2:23:56 PM5/2/18
to
I've used lsearch quite a bit but can't understand why this is not working as expected. See below:

Here is a simple list:
% set cmd_list {"show interface" " BREAK "}
"show interface" " BREAK "

Directly below, this works as expected:
% lsearch -regexp $cmd_list "\s*BREAK\s*"
1


(directly below) Why doesn't this match? I believe my regexp pattern says match if any list element begins with zero or more whitespaces, then contains the string BREAK followed by zero or more whitespace.
% lsearch -regexp $cmd_list "^\s*BREAK\s*"
-1
%


(directly below)Same problem with matching end of pattern:
% lsearch -regexp $cmd_list "\s*BREAK\s*$"
-1
%

Thanks in advance
Al

Don Porter

unread,
May 2, 2018, 2:59:29 PM5/2/18
to
On 05/02/2018 02:23 PM, asilver wrote:
> I've used lsearch quite a bit but can't understand why this is not working as expected.

You're suffering from double substitution, but not realizing it.

> Here is a simple list:
> % set cmd_list {"show interface" " BREAK "}
> "show interface" " BREAK"
>
> Directly below, this works as expected:
> % lsearch -regexp $cmd_list "\s*BREAK\s*"
> 1

The pattern you are matching is {s*BREAKs*}. Tcl does backslash
substitution in quoted words before [lsearch] ever sees the argument.
That matches because an empty string matches (s*) on either end and the
literal BREAK matches in the middle.

What you meant to code was:

% lsearch -regexp $cmd_list {\s*BREAK\s*}
1

When you make the same correction to your other examples:

% lsearch -regexp $cmd_list {^\s*BREAK\s*}
1
% lsearch -regexp $cmd_list {\s*BREAK\s*$}
1

Without the correction, they fail because anchoring to the string
beginning or end means the space sequences cannot be ignored and
the pattern (s*) does not match sequences of spaces.

--
| Don Porter Applied and Computational Mathematics Division |
| donald...@nist.gov Information Technology Laboratory |
| http://math.nist.gov/~DPorter/ NIST |
|______________________________________________________________________|

asilver

unread,
May 2, 2018, 3:45:47 PM5/2/18
to
Thank you Don, that's was it. As soon as you mentioned that you jarred my memory... Thanks Again.
0 new messages