1

我正在做一个小测试来尝试 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||||

这是正常的吗?如果是这样:有什么办法可以改变这种行为?

我尝试过的事情:

Ruby 版本:1.8.7
Ubuntu:10.04 (Lucid Lynx)

我会很感激你的任何想法。非常感谢。

4

1 回答 1

0

看起来回车符混淆了“+”量词。

下面匹配整行,包括回车(这会弄乱输出格式,应该修剪)

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

祝你好运。

于 2012-03-27T06:13:23.067 回答