我正在做一个小测试来尝试 Ruby 的 pty,但我做错了。我认为主要问题是正则表达式是非贪婪的。
这是一个名为inputs.rb
:
puts "Give me root@server password:"
password = gets.chomp()
puts "Thank you! Your password is: #{password}"
这是一个名为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
不幸的是,在打印输出时,我得到了这个:
The whole output is ||||
password1234
Thank you! Your password is: p||||
output1 = |
|
output1 = |password1234
|
output1 = |Thank you! Your password is: p|
为什么是它
Thank you! Your password is: p||||
而不是
Thank you! Your password is: password1234||||
?
这是正常的吗?如果是这样:有什么办法可以改变这种行为?
我尝试过的事情:
- rubular 上的正则表达式:它有效。
- 所有评论的替代方案:它们都不起作用(获取完整的密码)。
- http://www.42klines.com/2010/08/14/what-to-expect-from-the-ruby-expect-library.html
Ruby 版本:1.8.7
Ubuntu:10.04 (Lucid Lynx)
我会很感激你的任何想法。非常感谢。