【问题标题】:Non greedy regular expressions in Ruby: pty and expectRuby 中的非贪婪正则表达式:pty 和 expect
【发布时间】:2012-03-27 01:35:21
【问题描述】:

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

如果您有任何想法,我将不胜感激。非常感谢。

【问题讨论】:

  • 你应该精简你的问题以找出真正的问题。

标签: ruby regex expect pty non-greedy


【解决方案1】:

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

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

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

祝你好运。

【讨论】:

  • 非常感谢。我终于用 \r\n 代替了 \r 但感谢您指出这一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-15
  • 1970-01-01
  • 2011-08-29
  • 2011-04-27
  • 2010-10-20
  • 1970-01-01
相关资源
最近更新 更多