我正在做一些測試來嘗試Ruby的pty,但我無法正確理解它。我認爲主要的問題是正則表達式不貪婪。Ruby中非貪婪的正則表達式:pty和expect
這是一個名爲inputs.rb
程序:
puts "Give me [email protected] 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(/[email protected] 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(清醒山貓)
我會感激你可能有什麼想法。非常感謝你。
你應該減少你的問題,找出真正的問題。 – sawa 2012-03-27 01:48:40