0
votes

I am new to Expect and Tcl. I am writing a code using expect in Tcl to match a pattern alone(ie without the pattern being a sub string in a given string).Code is given below:

 package require Expect
 expect  "^hi$" { send "pattern matched" }; # hi is the pattern to be matched

But the code do not detect hi. If the code is modified as below it works when the pattern comes in the first part of the string

 package require Expect
 expect  "^hi" { send "pattern matched" }

If the code is modified as below, it is not working even though it is expected to match the pattern at the end of the string

 package require Expect
 expect  "hi$" { send "pattern matched" }

Am I doing anything wrong? Please help

2

2 Answers

0
votes

That is indeed a bit mysterious.

$ is the end of a string anchor and it looks like that the line end is captured before the end of the string. With this in mind you can do it with:

expect "Hi\n$" { puts "Wow" }

Be aware that \n is working on linux but maybe not on other console types!

0
votes

There are a few things that can go wrong, but the option most likely is that there's some sort of extra whitespace after the text that you are expecting; Expect sees all the characters, not just the printable ones. It could be a space, it could be a newline. If you know what it is, add that into what you are expecting. Otherwise, you need a more complex regular expression:

# RE in braces because of the backslash; \s matches *ALL* types of whitespace
expect {^hi\s*$}
send "found it!"

Another option is to switch RE matching modes. Expect operates in full-buffer mode by default (it's the only sensible option in the most complex scenarios) but you can put it into line-oriented:

# The ā€˜n’ is mnemonically for Newline-aware
expect {(?n)^hi$}
send "found it!"