Question

I was doing a little test to try Ruby's pty and I can't get it right. I think the main problem is that the regular expression is non-greedy.

This is a program called inputs.rb:

puts "Give me root@server password:"
password = gets.chomp()
puts "Thank you! Your password is: #{password}"

And this is a program called test.rb:

require 'pty'
require 'expect'

#$expect_verbose = true

#answer = %r/Thank you! Your password is: \w+/

PTY.spawn("ruby ./inputs.rb") do |reader, writer, pid|

   writer.sync = true

   reader.expect(/root@server password:/) do |output|
      writer.puts("password1234")
   end

   #reader.expect(answer) do |output|
   #reader.expect(/Thank you! Your password is: \w{6,}/) do |output|
   #reader.expect(/Thank you! Your password is: (\w+)/) do |output|
   reader.expect(/Thank you! Your password is: \w+/) do |output|
      puts "The whole output is ||||#{output}||||\n"
      output.first.each do |line|
         puts "output1 = |#{line}|\n"
      end
   end

end

Unfortunately, when printing the output I get this:
The whole output is ||||
password1234
Thank you! Your password is: p||||
output1 = |
|
output1 = |password1234
|
output1 = |Thank you! Your password is: p|

Why is it
Thank you! Your password is: p||||
instead of
Thank you! Your password is: password1234|||| ?

Is this normal? In case it is: is there any way to change this behaviour?

Things that I have tried:

Ruby version: 1.8.7
Ubuntu: 10.04 (Lucid Lynx)

I will appreciate any ideas you may have. Thank you very much.

Was it helpful?

Solution

Looks like the carriage return is confusing the "+" quantifier.

The below matches the entire line, including the carriage return (which messes up the output formatting and should be trimmed)

   reader.expect(/Thank you! Your password is: \w+\r/) do |output|

Good luck.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top