7

I'm having this poblem with a expect script. I want to capture when the output of a command is "0" and distinguish from other numbers or chains like "000" or "100"

my code is:

#!/usr/bin/expect -f
set timeout 3
spawn bash send "echo 0\n" 
expect {
-regexp {^0$} { send_user "\nzero\n" }  
-re {\d+} { send_user "\number\n"}
}
send "exit\n"

I have the follwing response:

spawn bash
echo 0

number

But the following regex don't work:

-regexp {^0$} { send_user "\nzero\n" }

if I change it to:

-regexp {0} { send_user "\nzero\n" }

works, but it also capture "00" "10" "1000" etc.

send "echo 100\n"
expect {
    -regexp {0} { send_user "\nzero\n" }
    -re {\d+} { send_user "\nnumber\n"}
}

Result:

spawn bash
echo 10

zero

I don't know what I'm doing wrong and I didn't found any from help on google. I also searched for similar problems resolved here I couldn't make any of it work on my code.

Update:

I tried the proposed fix code:

#!/usr/bin/expect -f
set timeout 3
spawn bash
send "echo 0\n"
expect {
    -regexp {\b0\b} { send_user "\nzero\n" }
    -re {\d+} { send_user "\nnumber\n"}
}
send "exit\n"

But I still having this response:

spawn bash
echo 0

number

Update 2

I also tried this line:

 -regexp {"^0\n$"} { send_user "\nzero\n" }

But I still having the same results.

Thanks in advance

Dedalo
  • 131
  • 1
  • 1
  • 8

3 Answers3

6

I could resolve the problem:

#!/usr/bin/expect -f
set timeout 3

spawn bash
send "echo 0\n"
expect -re "(\\d+)" {
    set result $expect_out(1,string)
}
if { $result == 0 } {
    send_user "\nzero\n";
} else {
    send_user "\nnumber\n";
}

send "exit\n"
Dedalo
  • 131
  • 1
  • 1
  • 8
0

Had a quick look at expect's documentation:

However, because expect is not line oriented, these characters match the beginning and end of the data (as opposed to lines) currently in the expect matching buffer.

Your regex should take into account the fact that you have line breaks.

If your data is 0\n, then you can use "^0\n$".

Sylverdrag
  • 8,898
  • 5
  • 37
  • 54
  • I tried to your approach, but I coudn't make it work. I really don't know what I'm doing wrong. – Dedalo Aug 13 '13 at 13:56
  • The only thing I can think of is that "echo" is not actually getting processed. To test that, try {echo} in the regex and see what it gives you. – Sylverdrag Aug 14 '13 at 04:44
-1

Try using word boundaries: \b0\b

JDiPierro
  • 802
  • 1
  • 9
  • 28