ruby - 在 Ruby 中提取部分字符串

标签 ruby

所以我得到了一个包含以下内容的文本文件:

Blade Runner (1982) [117 min] 
Full Metal Jacket (1987) [116 min] 
Monty Python and the Holy Grail (1975) [91 min] 
The Godfather (1972) [175 min]

必须把它变成这样:

Movie name: Blade Runner  
Movie release year: 1982 
Movie length (in mins): 117 

Movie name: Full Metal Jacket  
Movie release year: 1987 
Movie length (in mins): 116 

Movie name: Monty Python and the Holy Grail  
Movie release year: 1975 
Movie length (in mins): 91 

Movie name: The Godfather  
Movie release year: 1972 
Movie length (in mins): 175

首先我遍历每一行,然后我想我应该遍历字符串的每一部分,但这就是我卡住的地方,我该怎么做?我使用正则表达式吗?如何保存与正则表达式匹配的特定字符串?

这是代码的当前外壳,它将三个部分存储到变量中,这些变量用于初始化电影类,该电影类的 to_s 方法以所需格式打印。

我知道这在很多方面都不对,但这就是我寻求帮助的原因。 variable =/regex/是为变量分配正则表达式捕获的内容的行,当/regex/用于匹配正则表达式时。

class Movie
    def initialize (name, year, length) # constructor
        @name = name
        @year = year
        @length = length
    end

    def to_s    # returns string representation of object
        return "Movie Name: " + @name
            + "\nMovie release year: "
            + @year + "\nMovie Length (in min): "
            + @length + "\n"
    end
end

$movies = []
File.open("movies.txt").each do |line|
  if matches = /(.*)? \((\d+).*?(\d+)/.match(line)
    $movies << Movie.new(matches[1], matches[2], matches[3])
  end
end


for $movie in $movies do #what u got here is not index but the element in the array
    print $movie.to_s
end

编辑:

固定版本的代码,但末尾的打印循环不起作用。

Edit2:nownit 确实如此。谢谢 PeterPeiGuo!

最佳答案

m = /(.*)? \((\d+).*?(\d+)/.match("Blade Runner (1982) [117 min]")

关于ruby - 在 Ruby 中提取部分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8351219/

相关文章:

ruby - 有选择地使 JRuby 警告静音

ruby - 尝试循环遍历 Vagrant 框的哈希,失败

ruby - 为什么日期解析取决于分隔符?

ruby-on-rails - 如何使用以前版本的 Rspec 运行我的 Specs?

ruby - 将 seeds.rb 分成多个部分?

ruby - Ubuntu:如何使用 ruby​​ 应用程序添加 Systray 通知图标?

ruby-on-rails - Rails 中的caches_page,json 格式

带有 ca 认证的 Ruby https 在与 curl 一起工作时不起作用

Ruby bundle 打开,设置 $EDITOR

ruby-on-rails - rails : Devise : make `reset password` use `confirmation resend` if user is unconfirmed