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

Find a specific text segment within a file and than search for specific line in ruby

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

1)首先搜索包含关键词"Macros"

的一行

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

有什么建议吗?

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

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

您可以使用正则表达式:

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"]