Note that there are some explanatory texts on larger screens.

plurals
  1. PONon greedy regular expressions in Ruby: pty and expect
    text
    copied!<p>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.</p> <p>This is a program called <code>inputs.rb</code>:</p> <pre class="lang-rb prettyprint-override"><code>puts "Give me root@server password:" password = gets.chomp() puts "Thank you! Your password is: #{password}" </code></pre> <p>And this is a program called <code>test.rb</code>:</p> <pre class="lang-ruby prettyprint-override"><code>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 </code></pre> <p>Unfortunately, when printing the output I get this:<br> <code>The whole output is ||||<br> password1234<br> Thank you! Your password is: p||||<br> output1 = |<br> |<br> output1 = |password1234<br> |<br> output1 = |Thank you! Your password is: p|</code></p> <p>Why is it<br> <code>Thank you! Your password is: p||||</code><br> instead of<br> <code>Thank you! Your password is: password1234||||</code> ?</p> <p>Is this normal? In case it is: is there any way to change this behaviour?</p> <p>Things that I have tried:</p> <ul> <li>The regular expression on rubular: It works.</li> <li>All the commented alternatives: None of them work (get the complete password).</li> <li><a href="http://www.42klines.com/2010/08/14/what-to-expect-from-the-ruby-expect-library.html" rel="nofollow">http://www.42klines.com/2010/08/14/what-to-expect-from-the-ruby-expect-library.html</a></li> </ul> <p>Ruby version: 1.8.7<br> Ubuntu: 10.04 (Lucid Lynx) </p> <p>I will appreciate any ideas you may have. Thank you very much.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload