在文件中查找特定文本段,然后在ruby中搜索特定行

时间:2015-11-17 14:57:56

标签: ruby-on-rails ruby rake

我试图在文本文件中找到特定的文本段,而不是文本段中的特定行。算法应如下:

1)首先,搜索包含关键字"宏"

的行

2)下一个找到的行必须包含关键字" Name"

3)最后打印下一行

作为伪代码,我的意思是这样的:

File.open(file_name) do |f|
  f.each_line {|line|
    if line.include?("Macros")
      and if next line.include?("Name")
        print me the line after
    end

有什么建议吗?

2 个答案:

答案 0 :(得分:0)

我会使用布尔标志来记住我已经匹配条件的部分:

File.open(file_name) do |file|
  marcos_found = false
  name_found   = false

  file.each_line do |line|
    if line.include?('Macros')
      marcos_found = true 

    elsif found_marcos && line.include?("Name")
      name_found = true

    elsif marcos_found && name_found
      puts line
      break # do not search further or print later matches
    end
  end
end

答案 1 :(得分:0)

您可以使用正则表达式:

r = /
    \bMacros\b  # Match "Macros" surrounded by word breaks
    .*?$        # Match anything lazily to the end of the line
    [^$]*       # Match anything lazily other than a line break
    \bName\b    # Match "Name" surrounded by word breaks
    .*?\n       # Match anything lazily to the end of the line
    \K          # Discard everything matched so far
    .*?$        # Match anything lazily to the end of the line
    /x          # Extended/free-spacing mode

假设:

text = <<-_
You can use
Macros in C
to replace code.
Ruby doesn't
have Macros.
"Name That Tune"
was an old TV
show.
_

让我们把它写到文件:

FName = "test"
File.write(FName, text)
  #=> 104

将其读回字符串:

str = File.read(FName)
  #=> "You can use\nMacros in C\nto replace code.\nRuby doesn't\nhave " +
  #   "Macros.\n\"Name That Tune\"\nwas an old TV\nshow.\n"

并测试正则表达式:

text.scan r
  #=> ["was an old TV"]